在博客(python本地数据获取 网址:http://blog.csdn.net/sxingming/article/details/51333663)中,我们详细介绍了python中文件读写的各种方法。
本文通过5个具体例子,示例一下文件的读写操作。
1》将文件companies.txt中的字符串前加上序号1,2,3……后,写到另一个文件scompanies.txt中。
文件companies.txt中的内容如下图:
>>> f1=open(r'C:\Users\Administrator\Desktop\companies.txt','r')
>>> companyNames=f1.readlines()
>>> for i in range(0,len(companyNames)):
... companyNames[i]=str(i+1)+' '+companyNames[i]
...
>>> f1.close()
>>> f2=open(r'C:\Users\Administrator\Desktop\scompanies.txt','w')
>>> f2.writelines(companyNames)
>>> f2.close()
运行程序后,文件scompanies.txt中的内容如下图:
2》打开文件companies.txt,在尾部追加一行'alibaba',然后读出文件内容。
>>> f1=open(r'C:\Users\Administrator\Desktop\companies.txt','a+')
>>> f1.write('\n')
>>> f1.write('alibaba')
>>> f1.seek(0,0)
>>> l=f1.readlines()
>>> f1.close()
>>> l
['Apple Inc.\n', 'Google Inc.\n', 'Facebook,Inc.\n', 'Microsoft Corporation\n', 'alibaba']
3》打开文件companies.txt,在第二行后,添加一独立的新行'love python'。
>>> f=open(r"C:\Users\Administrator\Desktop\companies.txt",'r+')#注意打开模式
>>> n=2
>>> l=f.readlines()
>>> l
['Apple Inc.\n', 'Google Inc.\n', 'Facebook,Inc.\n', 'Microsoft Corporation\n', 'alibaba']
>>> l.insert(n,'love python\n')#字符串末尾记得写换行符
>>> l
['Apple Inc.\n', 'Google Inc.\n', 'love python\n', 'Facebook,Inc.\n', 'Microsoft Corporation\n', 'alibaba']
>>> f.seek(0)#将文件指针移到文件开头
>>> f.writelines(l)
>>> f.close()
插入新行后,文件内容如下:
4》读取整个文件的内容
可以直接使用readlines()函数,如下:
>>> f=open(r"C:\Users\Administrator\Desktop\companies.txt",'r')
>>> l=f.readlines()
>>> f.close()
>>> print l
['Apple Inc.\n', 'Google Inc.\n', 'love python\n', 'Facebook,Inc.\n', 'Microsoft Corporation\n', 'alibaba']
5》读取整个文件内容,不使用readlines()函数,如下:
>>> f=open(r"C:\Users\Administrator\Desktop\companies.txt",'r')
>>> lines=[]
>>> for line in f: #文件是一个可迭代对象
... lines.append(line)
...
>>> f.close()
>>> print lines
['Apple Inc.\n', 'Google Inc.\n', 'love python\n', 'Facebook,Inc.\n', 'Microsoft Corporation\n', 'alibaba']
(完)