python 檔案處理

2022-09-20 02:54:12 字數 2787 閱讀 2111

#檔案的讀寫:

## r:唯讀

f = open('

file.txt

','r

') #

r:唯讀

data =f.read()

print

(data)

f.close()

#及時關閉,釋放記憶體

open函式預設即為唯讀模式,故其中的 ' r ' 可不寫。檔案訪問結束後要及時close()。

## w:覆蓋檔案原始資料後寫入新資料

f = open('

file.txt

','w

') #

'w':覆蓋原資料來寫入。

f.write('

hahaha\n')

f.write(

'ha\n123\n345\n')

f.writelines([

'asd\n

','123

','1

']) #

只能是字串

f.close()

在『w』條件下,若open函式指定的檔案不存在,則會新建乙個該檔案來寫入資料。

## a:不覆蓋原始資料,只在原始資料後追加新資料(不可讀)

f = open('

file.txt

','a

')

其它操作方法同 ' w '。

# 使用with as 語句可避免使用f.close()

with open('

new.txt

', '

w') as f: #

等效於f = open('new.txt', 'w')

f.write('

hahaha\n')

with open(

'new.txt

') as f:

print(f.read())

#檔案在b模式下的讀寫:

b模式即以位元組的方式來讀寫檔案,b模式下的open函式無法指定其編碼方式。在b模式下,就要常常對字串和位元組進行編碼(encode)或解碼(decode)轉換:

字串------encode-----> bytes

bytes -------decode-----> 字串

## rb:以位元組方式讀檔案

新建file.txt檔案,其內容為:

123你好啊

f = open('

file.txt

','rb

') #

不能指定編碼方式,即不能新增encoding:'***'

print

(f.read())

print(f.read().decode('

gbk'))

上面第乙個print是直接輸出 f 的內容,故其輸出結果為位元組方式的檔案內容,結果如下:

b'

123\r\n\xc4\xe3\xba\xc3\xb0\xa1

' #

\r\n即回車,在linux中是\n

如果想要輸出其原本的資料形式,則需要解碼(decode)來實現,即第二個print。此處我們用了 『gbk』 編碼來解碼,其結果如下:

123你好啊

## wb:以位元組方式寫檔案

f = open('

test.py

','wb

')

在以位元組方式寫入檔案內容時,要注意寫入的資料必須是位元組格式,字串是不能寫入二進位制檔案的。所以當寫入字串時:

f.write('

123\n

')

程式會立刻報錯:

typeerror: a bytes-like object is required, not 'str'

正確寫入檔案主要有如下兩種方式:

f.write(bytes('

你好\n

', encoding = '

utf-8

')) #

bytes()可將字串按照指定編碼(此處為'utf-8')轉換成位元組形式

f.write('

1111\n

'.encode()) #

此處使用的是encode來將字串編碼成pytes

#其它檔案操作方法:

f.flush()     #

重新整理,以在寫了一堆資料後儲存檔案,類似於系統快捷鍵ctrl+s

f.seek(3) #

將檔案裡的游標位置從開頭移動3個位元組

f.seek(-3,2) #

此處2代表從檔案末尾移動游標,-3說明向前移動三個位元組。(注意:在2模式下,第乙個引數一定要加上-號)

#f = open('

a.txt

','r')

for i in

f:

print

(i)'''

這種方式迴圈時,是從檔案中每次拿一行資料,若使用:

for i in f.readlines():

print(i)

則程式會先生成乙個包含了檔案全部資料的列表,然後在列表中每次拿一行。因此在有些情況下會占用較大記憶體,產生浪費。

'''

python檔案處理

def cal input input.txt output output.txt cal方法為主程式,推薦這樣做而不是python.exe xx.py 預設引數為python目錄的兩個txt,如為其他檔案自己指定。infile file input,r 開啟源資料檔案 outfile file o...

python 檔案處理

1.開啟檔案 open a.txt 當前目錄下的a.txt open root a.txt 開啟某個目錄下的檔案 2.按行顯示檔案 a open a.txt a.readline ni hao n a.readline wo xianzai hen xiang ni n a.readline ni ...

Python檔案處理

open name mode buf read size readline size readlines size 這裡的size是指,io定義的default buffer size為單位大小 iter 迭代器迭代每行 write str writelines sequwence of strin...