[英]How to save a file with python
請我不是在尋找這個。 如何復制 Python 中的文件? 我得到了這個文件來保存,但我不知道如何 go 關於它。 使用下面的代碼,我可以將文本保存在數據變量中。 如何對其進行編碼,以便數據變量指向我想要在另一個選定位置重新保存的目錄中的文檔?
a = QFileDialog.getSaveFileName(MainWindow, "Save results", os.getenv("HOME"), "Save pdf(*.pdf);;Save csv(*.csv);;Save excel(*.xlsx);;Save text(*.txt)")
name = open(a[0],'w')
data = "This is my text"
name.write(data)
name.close()
您可以為此使用上下文管理器:
# Choose the new path for your file, example: r'Desktop\my_file.txt'
new_file_path = input("Location to store new file: ")
# use mode = 'a' to append to file, mode = 'w' to overwrite
with open(a[0], 'r') as read_file, open(new_file_path, 'a') as write_file:
data = read_file.readlines()
new_file_path.write(data)
看起來你只是想復制文件的內容,甚至在新文件中添加一些內容。 只需獲取所有行,對它們做任何你想做的事情,然后將它們保存到另一個文件中。
請注意,如果文件太大,將其全部加載到 memory 中不是一個好習慣,您可以通過逐行讀取和寫入迭代地執行此操作。
with open(a[0],'w') as infile:
lines = infile.readlines()
with open('newfilename', 'wb') as outfile:
outfile.writelines(lines)
感謝所有嘗試我的問題的人。 我能夠將兩者結合起來,我終於弄清楚了我想要什么。 我得到的解決方案是。
with open(a[0], 'w') as user_file_name:
user_file_name.writelines(open(the_existing_file_to_save))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.