pyqt5 操作txt文件的功能
时间: 2023-07-04 21:09:20 浏览: 311
PyQt5可以通过QFileDialog对话框来实现打开和保存txt文件的功能,具体步骤如下:
1. 导入需要的模块:
```python
from PyQt5.QtWidgets import QApplication, QWidget, QFileDialog
```
2. 创建一个QWidget窗口:
```python
app = QApplication(sys.argv)
window = QWidget()
```
3. 创建打开文件的函数,使用QFileDialog.getOpenFileName()方法:
```python
def open_file():
file_path, _ = QFileDialog.getOpenFileName(window, "Open Text File", "", "Text Files (*.txt)")
if file_path:
with open(file_path, 'r') as file:
text = file.read()
# 在文本编辑框中显示读取到的文本
text_edit.setText(text)
```
4. 创建保存文件的函数,使用QFileDialog.getSaveFileName()方法:
```python
def save_file():
file_path, _ = QFileDialog.getSaveFileName(window, "Save Text File", "", "Text Files (*.txt)")
if file_path:
with open(file_path, 'w') as file:
file.write(text_edit.toPlainText())
```
5. 创建一个文本编辑框:
```python
text_edit = QTextEdit()
```
6. 创建打开和保存按钮,并添加对应的函数:
```python
open_button = QPushButton("Open")
open_button.clicked.connect(open_file)
save_button = QPushButton("Save")
save_button.clicked.connect(save_file)
```
完整代码示例:
```python
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QFileDialog, QPushButton, QTextEdit
app = QApplication(sys.argv)
window = QWidget()
text_edit = QTextEdit()
def open_file():
file_path, _ = QFileDialog.getOpenFileName(window, "Open Text File", "", "Text Files (*.txt)")
if file_path:
with open(file_path, 'r') as file:
text = file.read()
# 在文本编辑框中显示读取到的文本
text_edit.setText(text)
def save_file():
file_path, _ = QFileDialog.getSaveFileName(window, "Save Text File", "", "Text Files (*.txt)")
if file_path:
with open(file_path, 'w') as file:
file.write(text_edit.toPlainText())
open_button = QPushButton("Open")
open_button.clicked.connect(open_file)
save_button = QPushButton("Save")
save_button.clicked.connect(save_file)
layout = QVBoxLayout()
layout.addWidget(text_edit)
layout.addWidget(open_button)
layout.addWidget(save_button)
window.setLayout(layout)
window.show()
sys.exit(app.exec_())
```
该示例创建了一个窗口,包含一个文本编辑框,和打开、保存按钮。用户可以打开txt文件并显示到文本编辑框中,也可以将编辑框中的内容保存为txt文件。
阅读全文
相关推荐


















