Python之檔案操作

2021-07-11 16:55:15 字數 2136 閱讀 3387

file =  open(filename, mode),mode預設為"r"

例如file = ope("test.txt", "r").以讀的方式開啟檔案.檔案操作完畢記得關閉.file.close()

其中,mode可以有以下選擇:

檔案test.txt的內容為:

11111111111-----aaaaaaaaa

22222222222-----bbbbbbbb

33333333333-----cccccccccc

read([size])size為讀取大小,單位為byte,不指定size的話則一次性讀全部內容

f = open("test.txt")

print f.read()

f.close()

'''11111111111-----aaaaaaaaa

22222222222-----bbbbbbbb

33333333333-----cccccccccc

'''

readline([size])按行讀取,如果指定了size,可能只返回一行的一部分

f = open("test.txt")

print f.readline()

f.close()

'''11111111111-----aaaaaaaaa

'''

readlines([size])把檔案的每一行作為list的乙個元素,返回整個list

f = open("test.txt")

print f.readlines()

f.close()

'''['11111111111-----aaaaaaaaa\n', '22222222222-----bbbbbbbb\n', '33333333333-----cccccccccc']

'''

fp.write(str)把str寫到檔案中,write()並不會在str後加上乙個換行符

fp.writelines(seq)把seq的內容全部寫到檔案中(多行一次性寫入).這個函式也只是忠實地寫入,不會在每行後面加上任何東西.

truncate()

僅當以r+,rb+,"w","wb","wb+"等以可寫模式開啟的檔案才能執行該功能

使用前先導入os模組.

練習:遞迴獲取目錄下所有檔名

def get_files(file_path):

files = os.listdir(file_path)

for file in files:

file_full_dir = os.path.join(file_path, file)

if os.path.isdir(file_full_dir):

get_files(file_full_dir)

else:

print os.path.join(file_path, file_full_dir)

很容易理解,對目錄下所有檔案和資料夾,如果是檔案則輸出,如果是資料夾遞迴查詢.

或者也可以用os.walk()來實現

def get_files(file_path):

for fpathe, dirs, fs in os.walk(file_path):

for f in fs:

print os.path.join(fpathe, f)

返回的是乙個三元tupple(dirpath, dirnames, filenames),

其中第乙個為起始路徑,第二個為起始路徑下的資料夾,第三個是起始路徑下的檔案.

dirpath是乙個string,代表目錄的路徑,

dirnames是乙個list,包含了dirpath下所有子目錄的名字,

filenames是乙個list,包含了非目錄檔案的名字.這些名字不包含路徑資訊,如果需要得到全路徑,需要使用 os.path.join(dirpath, name).

Python之檔案操作

使用open w 以寫入模式開啟,如果檔案存在將會刪除裡面的所有內容,然後開啟這個檔案進行寫入 a 以追加模式開啟,寫入到檔案中的任何資料將自動新增到末尾 fobj open home coder documents obama.txt 唯讀開啟 fobj fobj.close 關閉檔案 fobj ...

Python之檔案操作

建立目錄import os import errno defmkdir dir try os.makedirs dir except oserror as exc if exc.errno errno.eexist print the dir has been existed pass else r...

Python之 檔案操作

1 開啟檔案 f open hello.txt a 開啟 hello.txt 檔案 r 唯讀模式,開啟的檔案不存在的話,會報錯 w 只寫模式,會清空原來檔案的內容 a 追加模式 開啟的檔案不存在,會新建乙個檔案2 讀寫檔案 f open hello.txt a f.write joly,123 np...