file operations


#!/usr/bin/env python
#_*_ coding:utf-8 _*_

#data = open("yesterday",encoding="utf-8").read() #Open the file by ordinary method
f = open("yesterday",'r',encoding="utf-8") #File handle, r is read mode, the default is read mode if not write
data = f.read()
data2 = f.read()
print(data)
print('---------data2--------- --' ,data2) #The end of the file reading, the cursor is at the end of the file, and if you want to continue reading, you need to move the pointer back to the file header or other positions

write----overwrite the original file

#!/usr/bin/env python 
#-*- coding:utf-8 -*-
f = open('yesterday','w',encoding='utf -8')
f.write('I love Beijing Tiananmen Square ,\n')
f.write('The sun rises on Tiananmen Square')

Append ------ do not overwrite the original file

#!/usr/bin/env python
#_*_ coding:utf-8 _*_

f = open("yesterday2",'a',encoding="utf-8") #File handle, a=append append
f.write("I love Beijing Tiananmen...,\n")
f.write ("The sun rises on Tiananmen Square..")
f.close() #Close the file

 

append cannot read and write at the same time, only append

#!/usr/bin/env python
#-*- coding:utf-8 -*-
f = open('yesterday2','a',encoding='utf -8')
f.write("\nwhen i was young i listen to the radio\n")
data = f.read()
print('--read',data)
f.close()

read only first 3 lines

#!/usr/bin/env python
#-*- coding:utf-8 -*-
f = open('yesterday2','r',encoding='utf -8')
for i in range(3):
print(f.readline())

iterate through the file, print all lines

#!/usr/bin/env python 
#-*- coding:utf-8 -*-
f = open('yesterday2','r',encoding='utf -8')
for i in f.readlines():
print(i.strip()) #strip is to remove spaces and newlines


Efficient way to read files

#!/usr/bin/env python 
#-*- coding:utf-8 -*-
f = open('yesterday2','r',encoding='utf -8')
for i in f:
print(i. strip()) #strip is to remove spaces and newlines, print a line, overwrite a line in memory, using an iterator method, not a list

Print the file to line 10 for marking

#!/usr/bin/env python 
#-*- coding:utf-8 -*-
count = 0
f = open("yesterday2",'r',encoding="utf-8") #file handle
for i in f: #Print a line, covering a line in memory
if count == 9:
print('----I am the dividing line----')
count +=1
continue
print(i)
count +=1

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 










Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324457155&siteId=291194637