In the blog (python Local data acquisition URL: http://blog.csdn.net/sxingming/article/details/51333663), we detail the various ways in which files are read and written in Python.
In this article, 5 examples are given to illustrate the file's read and write operations.
1 The string in the file Companies.txt with the ordinal 1,2,3 ... Later, write to another file in Scompanies.txt.
The contents of the file Companies.txt are shown below:
>>> 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 ()
After running the program, the contents of the file Scompanies.txt are shown below:
2 Opens the file Companies.txt, appends a line of ' Alibaba ' to the tail, and reads the contents of the file.
>>> F1=open (R ' C:\Users\Administrator\Desktop\companies.txt ', ' + ')
>>> 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 ', ' a Libaba ']
3 Opens the file Companies.txt, after the second line, adds an independent new line ' 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 ()
When you insert a new row, the contents of the file are as follows:
4 Read the contents of the entire file
You can use the ReadLines () function directly, as follows:
>>> 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 reads the entire contents of the file without using the ReadLines () function, as follows:
>>> 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 ']
Finish