python3的檔案操作

2021-07-15 06:00:07 字數 1467 閱讀 1863

python的檔案操作和php的檔案很類似

file物件使用 open 函式來建立,open的引數:r表示讀,w寫資料,在寫之前先清空檔案內容,a開啟並附加內容,開啟檔案之後記得關閉

下表列出了 file 物件常用的函式:

序號方法及描述

file.close()

關閉檔案。關閉後檔案不能再進行讀寫操作。

file.flush()

重新整理檔案內部緩衝,直接把內部緩衝區的資料立刻寫入檔案, 而不是被動的等待輸出緩衝區寫入。

file.fileno()

返回乙個整型的檔案描述符(file descriptor fd 整型), 可以用在如os模組的read方法等一些底層操作上。

file.isatty()

如果檔案連線到乙個終端裝置返回 true,否則返回 false。

file.next()

返回檔案下一行。

file.read([size])

從檔案讀取指定的位元組數,如果未給定或為負則讀取所有。

file.readline([size])

讀取整行,包括 "\n" 字元。

file.readlines([sizehint])

讀取所有行並返回列表,若給定sizeint>0,返回總和大約為sizeint位元組的行, 實際讀取值可能比sizhint較大, 因為需要填充緩衝區。

file.seek(offset[, whence])

設定檔案當前位置

file.tell()

返回檔案當前位置。

file.truncate([size])

擷取檔案,擷取的位元組通過size指定,預設為當前檔案位置。

file.write(str)

將字串寫入檔案,沒有返回值。

file.writelines(sequence)

向檔案寫入乙個序列字串列表,如果需要換行則要自己加入每行的換行符。

test.py

#!/usr/bin/python3

spath="./test.txt";

f=open(spath,"w");

f.write("line 1 \n");

f.write("iine 2 \n");

f.writelines("line 3 \n");

f.write("iine 4 \n");

f.close();

f=open(spath,"r");

for line in f:

print("每行資料:%s"%line);

f.close();

執行結果

[root@mail pythoncode]# python3 test.py

每行資料:line 1

每行資料:iine 2

每行資料:line 3

每行資料:iine 4

Python 3 操作json 檔案

json 是一種輕量級的資料交換格式。易於人閱讀和編寫,同時也易於機器解析和生成。一般表現形式是乙個無序的 鍵值對 的集合。資料 官方文件 python操作json的其他方式 1.將字串轉化為json串 dumps import json a foo bar result json.dumps a ...

python3的檔案操作2

檔案的複製 複製函式copyfile 使用read write 實現拷貝 建立檔案hello.txt src open hello.txt w li hello world n hello china n src.writelines li src.close 把hello.txt拷貝到hello2...

python3 關於檔案的操作

使用open函式開啟乙個檔案。第乙個引數是檔案的路徑,如果檔案在程式當前路徑下,可以只寫檔名。file open filename.txt 可以通過新增第二個引數來決定檔案的開啟模式。寫模式,可以寫檔案內容,如果檔案不存在,會新建乙個檔案。open filename.txt w 讀模式,只能讀檔案內...