Basic file Operation:
#-*-coding:utf-8-*- fromIdlelib. IobindingImportencoding#Simple operation Simple reading and writing#Get file handle" "Open () can specify the opening mode, R: Default is read-only ' R ' r+: Read and write open (write is append) RB: Binary Way Read file W: can specify write-only file ' W ', w this way creates a file that overwrites the file you created, and use w+ sparingly: Read the way to open (write is in addition to the way), not commonly used WB: binary Write A: write-only way to open the file, appended to the end of the file, will not overwrite the original data A +: Append read ab: Append binary" "F= Open ("LYRICS1",'a')#Read the file#Data =f.read ()#print (data)#Write a fileF.write ("ha ha haha") F.close ()
Basic Operations
File Operation Method:
#-*-coding:utf-8-*-ImportSys,time" "#读取5行数据" "F= Open ("Lyrics",'R') forIinchRange (5):#print (F.readline ()) Passf.close ()" "#readlines () turn the file into a list------------not recommended!!! #不打印第3行" "F= Open ("Lyrics",'R') forIndex,lineinchEnumerate (F.readlines ()):ifindex== 3:#print ("------------This is the third line---------------") Continue#print (Line.strip ())f.close ()" "Read the recommended wording of a file, read one line at a time, and save only a row of data in memory" "Count=0;f= Open ("Lyrics",'R') forLineinchF:ifCount ==3: Count= Count+1#print ("This is the third line ++++++++++++++++++") Continue#print (line)Count = count+1f.close ()" "Pointer to the action file (cursor)" "F= Open ("Lyrics",'R')#gets the position of the current file pointer, the position of the file pointer is the number of characters,#The Read method can also specify the number of characters to read, such as F.read (5)Print(F.readline ())Print(F.readline ())Print(F.tell ())#move the file's cursor to the specified locationf.seek (0)Print(F.readline ()) F.close ()#Get file namef = open ("Lyrics",'R')Print(F.name) f.close ()" "Refreshes the file and stores the memory file to disk when the file is written" "F= Open ("Lyrics",'a') F.write ("AAA") F.flush () f.close ()#Flush also has a role, is the Linux system installation software when the progress bar forIinchRange (20): Sys.stdout.write ("#") #RefreshSys.stdout.flush ()#Wait 0.1 secondsTime.sleep (0.1)" "truncate file" "F= Open ("LYRICS1",'a') F.truncate (10) F.close ()#Automatically close filesWith open ("LYRICS1",'r+') as F: forLineinchF:Print(line)
Method
Python file operations