日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

python 档案管理系统_Python 写入档案的 4 个方法

發(fā)布時間:2023/12/2 python 48 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python 档案管理系统_Python 写入档案的 4 个方法 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

在 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

檔開啟檔案后, 可以用輸出文字的 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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。