python檔案txt讀寫

2021-10-17 04:51:00 字數 2345 閱讀 4797

在鍵盤隨便敲了幾個字並建立了乙個文字檔案(1.txt)

我們要使用python將其進行讀寫操作

#1、檔案讀寫操作:讀檔案1.txt

#使用open和read:

f=open

("1.txt"

)print

(f.read())

f.close(

)

輸出:

de鍝堝搱dfafadsfasdfasd

fasdfasdfjasdkhfasdfas

唯讀前 五個字元:

#2、唯讀前五個字元:

f=open

("1.txt"

,"r"

)print

(f.read(5)

)

輸出:de鍝堝搱

#3、以迴圈的方式一行行的列印:

f=open

("1.txt"

,"r"

)for x in f:

print

(x)

輸出:

de鍝堝搱dfafadsfasdfasd

fasdfasdfjasdkhfasdfas

f=

open

("1.txt"

,"r"

)print

(f.readline())

f.close(

)

輸出:[『de鍝堝搱dfafadsfasdfasd\n』, 『fasdfasdfjasdkhfasdfas』]

#開啟檔案——寫入新的內容到檔案——關閉檔案——重新開啟檔案讀取並檢視內容:

f=open

("1.txt"

,"a"

)f.write(

"\n hello world guguguan"

)f.close()f=

open

("1.txt"

,"r"

)for x in f:

print

(x)f.close(

)

輸出:de鍝堝搱dfafadsfasdfasd

fasdfasdfjasdkhfasdfas

hello world guguguan

#建立檔案:在檔案沒有被建立的情況下會自動重新建立乙個新的檔案:

f=open

("1.txt"

,"x"

)#如果檔案已經存在又重新建立的話會報錯:

f=open

("1.txt"

,"w"

)#w模式不會像x模式一樣會報錯

輸出:--

----

----

----

----

----

----

----

----

----

----

----

----

----

----

----

----

----

----

-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'

檔案刪除:使用os模組,同時還能對資料夾進行刪除:

#刪除檔案:

import os

os.remove(

"12.txt"

)

#刪除檔案之前可以檢視一下檔案存在的狀態:

import os

if os.path.exists(

"12.txt"):

os.remove(

"12.txt"

)else

:print

("the file does not exist"

)

輸出: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...