python的文件操作方法

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.py
 2 #将‘TeleAddressBook.txt’和‘EmailAddressBook.txt’中的数据合并
 3 
 4 def main():
 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,存入相应的列表中
20     for i in s1:
21         e = i.split()
22         list1_name.append(str(e[0].decode("gbk")))
23         list1_tel.append(str(e[1].decode("gbk")))
24     #遍历字符串列表s2,存入相应的列表中
25     for i in s2:
26         e = i.split()
27         list2_name.append(str(e[0].decode("gbk")))
28         list2_email.append(str(e[1].decode("gbk")))
29 
30     #进行操作
31     lines = []
32     lines.append("姓名	电话		邮箱
")
33     #遍历list_name列表中的名字,并判断列表2中是否有该名字,如果有,合并,如果没有,无邮箱
34     for i in range(len(list1_name)):
35         s = ''
36         if list1_name[i] in list2_name:
37             j = list2_name.index(list1_name[i])
38             s = '	'.join([list1_name[i],list1_tel[i],list2_email[j]])
39             s += '
'
40         else:
41             s = '	'.join([list1_name[i],list1_tel[i],"  ----  "])
42             s += '
'
43         lines.append(s)
44     #操作列表2中剩余的名字
45     for i in range(len(list2_name)):
46         s = ''
47         if list2_name[i] not in list1_name:
48             s = '	'.join([list2_name[i],'  -----  ',list2_email[i]])
49             s += '
'
50         lines.append(s)
51     #将列表写入对应的文件中,关闭所有文件
52     f3 = open("AddressBook.txt",'w')
53     f3.writelines(lines)
54     f3.close
55     f1.close
56     f2.close
57 
58 if __name__ == "__main__":
59     main()

 这个程序中的一些函数:

  str.join(sequence)  将序列中的元素以指定的字符连接生成一个新的字符串。

  

str = '-'
seq =( 'a',''b','c'
print(str.join(seq))

结果:
a-b-c

‘ '   转义字符,表示制表符,即四个空格。

原文地址:https://www.cnblogs.com/wobu/p/7468548.html