在 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) |