pyqt5 保存txt文本 不删除之前的内容
时间: 2023-12-18 07:04:45 浏览: 37
如果您希望在保存新内容时不删除之前的内容,可以将打开文件的模式设置为追加模式,即'a'。这样,新的内容将被追加到文件的末尾而不是覆盖之前的内容。以下是示例代码:
```python
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QTextEdit, QAction, QFileDialog
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.textEdit = QTextEdit()
self.setCentralWidget(self.textEdit)
saveFile = QAction('Save', self)
saveFile.setShortcut('Ctrl+S')
saveFile.triggered.connect(self.save)
menubar = self.menuBar()
fileMenu = menubar.addMenu('File')
fileMenu.addAction(saveFile)
self.setGeometry(300, 300, 350, 300)
self.setWindowTitle('Text Editor')
self.show()
def save(self):
filename, _ = QFileDialog.getSaveFileName(self, 'Save File', '', 'Text Files (*.txt);;All Files (*)')
if filename:
with open(filename, 'a') as f:
text = self.textEdit.toPlainText()
lines = text.split('\n')
for line in lines:
f.write(line + '\n')
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MainWindow()
sys.exit(app.exec_())
```
这个例子与前面的例子非常相似,不同之处在于,我们使用了打开文件的模式'a',以便将新的内容追加到文件末尾,而不是覆盖之前的内容。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)