1、檢查文件夾是否存在(不存在創建),在當前文件夾下的指定目錄創建txt文件並寫入數據:
import os #文件操作相關
root_path = os.path.dirname(os.path.realpath(__file__))+'\\'+'HISTORY_DATA'
if not (os.path.exists(root_path)):
os.makedirs(root_path)
filename = root_path + '\\' + currtime + '.txt'
with open(filename, 'a') as file_object:
print(data,file=file_object)
#以日期方式命名,注意':''/'等是windows文件命名的非法字符,命名的時候需要注意
#否則會出現OSError: [Errno 22]Invalid argument:
currtime = time.strftime('%Y%m%d-%Hh%Mm%Ss', time.localtime(time.time()))
#'\'是轉義符,在字符串前面加r可以自動將轉義字符進行轉義
#等價於:'D:\\Users\\JN\\PycharmProjects\\App\\HISTORY_DATA'
root_path=r'D:\Users\JN\PycharmProjects\App\HISTORY_DATA'
filename=root_path+'\\'+currtime+'.txt'
2、pyqt5窗體風格
#查看支持的窗體風格:
print(QStyleFactory.keys())
#設置窗體風格:
QApplication.setStyle("Fusion")
3、QTableView單行不允許編輯的方法
#在qtdesigner中設置這個選項就可以了
setEditTriggers(QAbstractItemView::NoEditTriggers);
#彈出提示性的窗口
QMessageBox.critical(self,"錯誤","請檢查端口號")
#有選擇的
reply = QMessageBox.question(self,
'提示',#標題框名稱
"是否要退出系統?",#顯示信息
QMessageBox.Yes | QMessageBox.No, #自定義按鈕
QMessageBox.Yes) #默認按鈕
if reply == QMessageBox.Yes:
self.close_all()
event.accept()
else:
event.ignore()
#窗口類型
QMessageBox::information(this, tr("Title"), tr("Content"));
QMessageBox::question(this, tr("Title"), tr("Content"));
QMessageBox::warning(this, tr("Title"), tr("Content"));
QMessageBox::critical(this, tr("Title"), tr("Content"));
QMessageBox::about(this, tr("Title"), tr("Content"));
5、QTableView
參考了很多https://blog.csdn.net/jia666666/article/details/81624259
參考了一些https://blog.csdn.net/cloveses/article/details/80943496
#將表格數據導入到txt文件(當前目錄下的某一文件夾)
def history_to_txt(self):
r=self.model.rowCount()
c=self.model.columnCount()
currtime = time.strftime('%Y%m%d-%Hh%Mm%Ss', time.localtime(time.time()))
root_path = os.path.dirname(os.path.realpath(__file__))+'\\'+'HISTORY_DATA'
if not (os.path.exists(root_path)):
os.makedirs(root_path)
filename = root_path + '\\' + currtime + '.txt'
for i in range(r):
for j in range(c):
item=self.model.index(i, j)
with open(filename, 'a') as file_object:
print(item.data(),file=file_object)
about_message='導出已完成,\n文件路徑:'+filename
QMessageBox.about(self,'提示',about_message)
6、TableWidget
沒試過,但是感覺寫的很好https://www.jianshu.com/p/962b572a216c
7、導出爲excel文件(使用Python寫入數據到Excel文件中)