在鍵盤隨便敲了幾個字並建立了乙個文字檔案(1.txt)
我們要使用python將其進行讀寫操作
輸出:#1、檔案讀寫操作:讀檔案1.txt
#使用open和read:
f=open
("1.txt"
(f.read())
f.close(
)
de鍝堝搱dfafadsfasdfasd
fasdfasdfjasdkhfasdfas
唯讀前 五個字元:
輸出:de鍝堝搱#2、唯讀前五個字元:
f=open
("1.txt"
,"r"
(f.read(5)
)
輸出:#3、以迴圈的方式一行行的列印:
f=open
("1.txt"
,"r"
)for x in f:
(x)
de鍝堝搱dfafadsfasdfasd
fasdfasdfjasdkhfasdfas
輸出:[『de鍝堝搱dfafadsfasdfasd\n』, 『fasdfasdfjasdkhfasdfas』]f=
open
("1.txt"
,"r"
(f.readline())
f.close(
)
輸出:de鍝堝搱dfafadsfasdfasd#開啟檔案——寫入新的內容到檔案——關閉檔案——重新開啟檔案讀取並檢視內容:
f=open
("1.txt"
,"a"
)f.write(
"\n hello world guguguan"
)f.close()f=
open
("1.txt"
,"r"
)for x in f:
(x)f.close(
)
fasdfasdfjasdkhfasdfas
hello world guguguan
#建立檔案:在檔案沒有被建立的情況下會自動重新建立乙個新的檔案:
f=open
("1.txt"
,"x"
)#如果檔案已經存在又重新建立的話會報錯:
f=open
("1.txt"
,"w"
)#w模式不會像x模式一樣會報錯
檔案刪除:使用os模組,同時還能對資料夾進行刪除:輸出:--
----
----
----
----
----
----
----
----
----
----
----
----
----
----
----
----
----
----
-fileexistserror traceback (most recent call last)
input-25
-d992b6bf7061>
in1#在檔案沒有被建立的情況下會自動重新建立乙個新的檔案:--
-->
2 f=
open
("1.txt"
,"x"
)3 f=
open
("1.txt"
,"w"
)fileexistserror:
[errno 17
] file exists:
'1.txt'
#刪除檔案:
import os
os.remove(
"12.txt"
)
輸出:the file does not exist;#刪除檔案之前可以檢視一下檔案存在的狀態:
import os
if os.path.exists(
"12.txt"):
os.remove(
"12.txt"
)else
("the file does not exist"
)
Python 讀寫txt檔案
1 讀取 usr bin python coding utf 8 import os str r c users d1 desktop test.txt f open str,r content f.read print content f.close 2 寫入 str c users d1 des...
Python讀寫txt檔案
最近,我在嘗試用python製作乙個簡單的桌面軟體,但其中遇見幾個小問題想給大家分享一下 一般檔案讀寫都是這樣的 讀取 f open test.txt r txt f.read f.close 寫入with open test.txt w as f f.write nothing f.close那,...
python讀寫txt檔案
整理平常經常用到的檔案物件方法 f.readline 逐行讀取資料 方法一 1 f open tmp test.txt 2 f.readline 3 hello girl n 4 f.readline 5 hello boy n 6 f.readline 7 hello man 8 f.readli...