PyQt5读写文件
一、读写txt文件,指定文件数据类型
def my_open(self):
my_file_path = QFileDialog.getOpenFileName(None, '选择文件', r'C:\Users\Administrator\Desktop','Excel files(*.txt)')
with open(my_file_path[0]) as f:
my_file = f.read()
self.textEdit.setText(my_file)
def my_save(self):
my_data = self.textEdit.toPlainText()
my_file = QFileDialog.getSaveFileName(None,'文件保存',r'C:\Users\Administrator\Desktop','Excel files(*.txt)')
fs = open(my_file[0],'a+')
fs.write(my_data)
fs.close()
二、读取Word文件:
def my_open(self): from win32com import client as wc word = wc.Dispatch('Word.Application') # 不打开word程序 word.Visible = 0 my_file_path = QFileDialog.getOpenFileName(None, '选择文件', r'C:\Users\Administrator\Desktop',"word文件(*.docx , *.doc))") myworddoc = word.Documents.Open(my_file_path[0]) #获取有多少段落 my_count = myworddoc.Paragraphs.Count #循环取出段落,显示到显示框中 for i in range(my_count): my_pr = myworddoc.Paragraphs[i].Range self.textEdit.append(my_pr.text) myworddoc.Close()
或者是:
def my_open(self): import docx my_file_path = QFileDialog.getOpenFileName(None, '选择文件', r'C:\Users\Administrator\Desktop',"word文件(*.docx , *.doc))") doc = docx.Document(my_file_path[0]) for i in doc.paragraphs: self.textEdit.append(i.text)
三、读取Ecxle文件一样的操作,方法比较多如xlrd pandas等等的,不做记录