在 Python 寫入檔案內容跟讀取檔案差不多, 也很簡單方便,以下會介紹用 Python 逐行讀取檔案內容的 4 種方法。
在看例子前先要了解開啟檔案的參數, 一般上讀取檔案會用 “r”, 即唯讀的意思, 如果要寫入檔案, 分別可以用 “w” (即 write 的意思) 或 “a” (即 append 附加的意思), 兩者的分別在於: 如果檔案原本已經存在, “w” 會將寫入的內容直接覆蓋原來的檔案內容; 而 “a” 則會在原來的內容後面加入新內容。兩者不可以混淆, 如果原本要用 “a” 而用錯了 “w”, 會使原來的檔案內容錯誤刪除。
以下所有例子會以 “a” 作為開啟檔案選項。
write
1 2 3 4 5 6 7 8 9 10 |
#!/usr/bin/python # 開啟檔案 fp = open("filename.txt", "a") # 寫入 This is a testing! 到檔案 fp.write("This is a testing!") # 關閉檔案 fp.close() |
檔開啟檔案後, 可以用輸出文字的 print 寫入檔案, 只是將原本輸出到顯示器改為檔案:
1 2 3 4 5 6 7 8 9 10 |
#!/usr/bin/python # 開啟檔案 fp = open("filename.txt", "a") # 寫入 This is a testing! 到檔案 print >>fp, "This is a testing!" # 關閉檔案 fp.close() |
writelines
可以將 array 的內容一次過寫入寫案, 但要自行加入 “\n” 到每一個換行:
1 2 3 4 5 6 7 8 9 10 11 |
#!/usr/bin/python # 開啟檔案 fp = open("filename.txt", "a") # 將 lines 所有內容寫入到檔案 lines = ["One\n", "Two\n", "Three\n", "Four\n", "Five\n"] fp.writelines(lines) # 關閉檔案 fp.close() |
with
用 wite 寫入檔案, 跟上面最大分別是, 不用 close() 關閉檔案:
1 2 3 4 5 6 7 |
#!/usr/bin/python with open(in_filename) as in_file, open(out_filename, 'a') as out_file: for line in in_file: ... ... out_file.write(parsed_line) |
No Responses