PyQt學習筆記 開啟檔案並從中讀取資料(高階篇)

2021-09-18 00:01:16 字數 2040 閱讀 4350

1 本文實現了開啟 txt、word、excel 格式檔案

2 讀取檔案內容

3 並列印到text.browser上

import docx

from xlrd import open_workbook

@pyqtslot(

)def

on_menu_files_open_triggered

(self)

:## win32com 對python3.x 支援效果不好,棄用之

# from win32com import client as wc

# word.visible = 0

print

("開啟"

) dialog = qfiledialog(

) my_file_path = dialog.getopenfilename(self,

"開啟檔案"

,"e:\\7program\\pycharm\\pyqt\\eric6-19.03\\workspace\\")[

0]print

(my_file_path)

if my_file_path[-4

:]=='.doc'

or my_file_path[-5

:]=='.docx'

:# my_worddoc = word.documents.open(my_file_path.replace('/', '\\'))

# print(type(my_worddoc))

# my_count = my_worddoc.paragraph.count

# for i in range(my_count):

# my_pr = my_worddoc.paragraph[i].range

# print(my_pr.text)

# my_worddoc.close()

## 採用 python-docx

# my_doc = docx.document(my_file_path.replace('/', '\\'))

# # print(my_doc.paragraphs[0].text)

# for my_paragraph in my_doc.paragraphs:

# print(my_paragraph.text)

'/',

'\\'))

)elif my_file_path.endswith(

'.xlsx'):

print

('excel!'

) wb = open_workbook(my_file_path.replace(

'/',

'\\'))

for s in wb.sheets():

for row in

range

(s.nrows)

:for col in

range

(s.ncols)

:print

(s.cell(row, col)

.value)

elif my_file_path[-4

:]=='.txt'

: f =

open

(my_file_path[0]

,'r'

, encoding=

"utf-8"

) my_data = f.read(

) f.close(

)else

: qmessagebox.information(self,

'information'

,'不支援的檔案格式'

)

1 win32com 對python3.x 支援效果不好 建議使用python-docx、xlrd、xlwt 第三方庫

2 encoding

3 path "/" 轉義

4 cell 類的用法

5 具體可以參考官方庫文件

python讀取csv檔案,並從中提取想要的資料列

def read test with open wine data.csv r as f data f.readlines 按行讀取資料 data data 1 result for i in data i list i.split 使用逗號分割方法分割 try i list 7 i list 8 ...

pyqt 學習筆記

coding utf8 import sys from pyqt4 import qtgui,qtcore class my button qtgui.qwidget def init self,parent none qtgui.qwidget.init self self.setwindowti...

pyqt 通過notepad開啟中文檔案

在qtreeview中通過 indexitem self.model.index index.row 0,index.parent filepath self.model.filepath indexitem 可以獲得檔案路徑,然後通過 if os.path.isfile u str unicode...