python 档案管理系统_Python 写入档案的 4 个方法
在 Python 寫入檔案內(nèi)容跟讀取檔案差不多, 也很簡單方便,以下會介紹用 Python 逐行讀取檔案內(nèi)容的 4 種方法。
在看例子前先要了解開啟檔案的參數(shù), 一般上讀取檔案會用 “r”, 即唯讀的意思, 如果要寫入檔案, 分別可以用 “w” (即 write 的意思) 或 “a” (即 append 附加的意思), 兩者的分別在于: 如果檔案原本已經(jīng)存在, “w” 會將寫入的內(nèi)容直接覆蓋原來的檔案內(nèi)容; 而 “a” 則會在原來的內(nèi)容后面加入新內(nèi)容。兩者不可以混淆, 如果原本要用 “a” 而用錯了 “w”, 會使原來的檔案內(nèi)容錯誤刪除。
以下所有例子會以 “a” 作為開啟檔案選項。
write
#!/usr/bin/python
# 開啟檔案
fp = open("filename.txt", "a")
# 寫入 This is a testing! 到檔案
fp.write("This is a testing!")
# 關(guān)閉檔案
fp.close()
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!")
# 關(guān)閉檔案
fp.close()
檔開啟檔案后, 可以用輸出文字的 print 寫入檔案, 只是將原本輸出到顯示器改為檔案:
#!/usr/bin/python
# 開啟檔案
fp = open("filename.txt", "a")
# 寫入 This is a testing! 到檔案
print >>fp, "This is a testing!"
# 關(guān)閉檔案
fp.close()
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!"
# 關(guān)閉檔案
fp.close()
writelines
可以將 array 的內(nèi)容一次過寫入寫案, 但要自行加入 “\n” 到每一個換行:
#!/usr/bin/python
# 開啟檔案
fp = open("filename.txt", "a")
# 將 lines 所有內(nèi)容寫入到檔案
lines = ["One\n", "Two\n", "Three\n", "Four\n", "Five\n"]
fp.writelines(lines)
# 關(guān)閉檔案
fp.close()
1
2
3
4
5
6
7
8
9
10
11
#!/usr/bin/python
# 開啟檔案
fp=open("filename.txt","a")
# 將 lines 所有內(nèi)容寫入到檔案
lines=["One\n","Two\n","Three\n","Four\n","Five\n"]
fp.writelines(lines)
# 關(guān)閉檔案
fp.close()
with
用 wite 寫入檔案, 跟上面最大分別是, 不用 close() 關(guān)閉檔案:
#!/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)
1
2
3
4
5
6
7
#!/usr/bin/python
withopen(in_filename)asin_file,open(out_filename,'a')asout_file:
forlineinin_file:
...
...
out_file.write(parsed_line)
你可能感興趣的內(nèi)容:
總結(jié)
以上是生活随笔為你收集整理的python 档案管理系统_Python 写入档案的 4 个方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: iCloud 钥匙串是什么iCloud
- 下一篇: python运行结果闪退_Pyhton