python的檔案操作方法

2022-05-29 18:45:18 字數 2604 閱讀 5384

python的檔案操作方法:

file.readline()    讀取下一行檔案,返回含有內容的字串

file.readlines() 讀取整個檔案,返回乙個字串列表

file.read()  讀取整個檔案,返回乙個字串

f = open("filename","mode")  開啟乙個檔案,mode 有:"r",'rb','r+','w','wb','a','ab'

開啟檔案進行操作後,需要關閉檔案,釋放記憶體,檔案才會匯入到磁碟中,才會顯示變化

f.close()  關閉檔案

wih open("filename","mode") as f :

f.readlines()

這種方法不用關閉檔案。還不知道原理是什麼.....

f.write()   寫入乙個字串到檔案中

f.writelines()  對列表進行操作,支援字串列表

1

#addressbook.py2#

將『teleaddressbook.txt』和『emailaddressbook.txt』中的資料合併34

defmain():5#

開啟檔案

6 f1 = open("

teleaddressbook.txt

","rb")

7 f2 = open("

emailaddressbook.txt

","rb")

8#設定空列表

9 list1_name =

10 list2_name =

11 list1_tel =

12 list2_email =13#

跳過第一行

14 a1 =f1.readline()

15 a2 =f2.readline()16#

讀取檔案

17 s1 =f1.readlines()

18 s2 =f2.readlines()19#

遍歷字串列表s1,存入相應的列表中

20for i in

s1:21 e =i.split()

gbk"

)))gbk

")))24#

遍歷字串列表s2,存入相應的列表中

25for i in

s2:26 e =i.split()

gbk"

)))gbk

")))

2930

#進行操作

31 lines =

姓名\t**\t\t郵箱\n")

33#遍歷list_name列表中的名字,並判斷列表2中是否有該名字,如果有,合併,如果沒有,無郵箱

34for i in

range(len(list1_name)):

35 s = ''

36if list1_name[i] in

list2_name:

37 j =list2_name.index(list1_name[i])

38 s = '\t'

.join([list1_name[i],list1_tel[i],list2_email[j]])

39 s += '\n'

40else

:41 s = '

\t'.join([list1_name[i],list1_tel[i],"

---- "])

42 s += '\n'

4344

#操作列表2中剩餘的名字

45for i in

range(len(list2_name)):

46 s = ''

47if list2_name[i] not

inlist1_name:

48 s = '

\t'.join([list2_name[i],'

-----

',list2_email[i]])

49 s += '\n'

5051

#將列表寫入對應的檔案中,關閉所有檔案

52 f3 = open("

addressbook.txt

",'w')

53f3.writelines(lines)

54f3.close

55f1.close

56f2.close

5758

if__name__ == "

__main__":

59 main()

這個程式中的一些函式:

str.join(sequence)  將序列中的元素以指定的字元連線生成乙個新的字串。

str = '-'

seq =( '

a',''b'

,'c'

)print

(str.join(seq))

結果:a-b-c

『\t'   轉義字元,表示製表符,即四個空格。

python檔案操作方法

import os os 系統模組 裡面有很多關於檔案操作相關的方法 1.os.getcwd 方法是獲得當前的工作路徑 now path os.getcwd print now path 2.os.listdir 方法是列出該路徑下所有檔案及資料夾 print os.listdir now path...

Python檔案操作方法

python中對檔案 資料夾 檔案操作函式 的操作需要涉及到os模組和shutil模組。得到當前工作目錄,即當前python指令碼工作的目錄路徑 os.getcwd 返回指定目錄下的所有檔案和目錄名 os.listdir 函式用來刪除乙個檔案 os.remove 刪除多個目錄 os.removedi...

python檔案的讀寫操作方法

這裡可以學到 檔案的最基本操作,檔案的開啟,以及讀檔案內容,寫檔案內容。1.新建.txt檔案 2.新建python檔案 3.在python檔案中對檔案的讀寫基本操作 開啟檔案 用 r 讀 f open test.txt r encoding utf 8 讀第一行 data f.readline pr...