This article mainly introduces the Python file operation of the details and examples of relevant information, I hope that through this article you can understand the knowledge of Python file operation, the need for friends can refer to the following
A detailed description of Python file operations and examples
One, the file operation
1, the document operation process
Open the file, get the file handle and assign a value to a variable
Manipulating a file with a handle
Close File
The existing files are as follows:
Last night the cold family Meconematidae from not live. Surprised to return to Trinidad Dream, has shift. Get up and walk around the steps alone. People quietly, the curtain outside the moon Dim Ming. For fame, old mountain pine bamboo old, resistance return journey. Want to Shang the mind. The bosom is few, the chord is broken who listens. f = open (' small Mountains ') #打开文件data =f.read () #获取文件内容f. Close () #关闭文件
Note: If in the Win,hello file is UTF8 saved, opening the file when the open function is opened by the operating system file, and the win operating system is the default GBK encoding, so the direct opening will be garbled, need f=open (' Hello ', encoding= ' UTF8 '), if the hello file is GBK saved, open it directly.
2. File Open mode
Character meaning
' R ' open for reading (default) ' W ' open for writing, truncating the file first ' x ' create a new file and open it For writing ' A ' open for writing, appending to the end of the file if it exists ' B ' binary mode ' t ' text mode (d efault) ' + ' open a disk file for updating (reading and writing) ' U ' Universal newline mode (deprecated)
The three most basic modes are introduced first:
# f = open (' Small Mountains 2 ', ' W ') #打开文件 # f = open (' Small Mountains 2 ', ' a ') #打开文件 # f.write (' Mo 1\n ') # f.write (' White up Junior Head 2\n ') # f.write (' empty mournful!3 ')
3, file specific operation
f = open (' small Mountains ') #打开文件 # data1=f.read () #获取文件内容 # data2=f.read () #获取文件内容 # # print (data1) # print (' ... ', data2) # Data=f.read (5) #获取文件内容 # Data=f.readline () # data=f.readline () # Print (f.__iter__ (). __next__ ()) # for I in range (5): # Print (F.readline ()) # data=f.readlines () # for lines in F.readlines (): # print (line) # Here's the problem: print all rows, plus the 3rd line followed by: ' End 3 ' # for Index,line in enumerate (F.readlines ()): # If index==2:# line= ". Join ([Line.strip (), ' End 3 ']) # print (Line.strip ()) #切记: We must all use the following # count=0 # f:# if count==3:# line= '. Join ([Line.strip (), ' End 3 ']) # print (Line.strip ()) # count+=1# print (F.tel L ()) # Print (F.readline ()) # Print (F.tell ()) #tell对于英文字符就是占一个, three Chinese characters, different from Read (). # Print (F.read (5)) #一个中文占三个字符 # Print (F.tell ()) # F.seek (0) # Print (F.read (6)) #read后不管是中文字符还是英文字符, all in one unit, read (6), reading 6 Chinese characters at the moment #terminal on the action: F = open ( ' Little Mountains 2 ', ' W ') # f.write (' Hello \ n ') # F.flush () # F.write (' World ') # App: progress bar # import time,sys# for I in range: # sys.stdout. Write ("*") # # Sys.stdout.flush () # time.sleep (0.1) # f = open (' Small Mountains 2 ', ' W ') # f.truncate () #全部截断 # f.truncate (5) #全部截断 # Print (F.isatty ()) # Print (F.seekable ()) # Print ( F.readable ()) F.close () #关闭文件
Next we continue to expand the file mode:
# f = open (' Small Mountains 2 ', ' W ') #打开文件 # f = open (' Small Mountains 2 ', ' a ') #打开文件 # f.write (' Mo 1\n ') # f.write (' White up Junior Head 2\n ') # f.write (' empty mournful!3 ') # F.clos E () #r +,w+ mode # f = open (' Small Mountains 2 ', ' r+ ') #以读写模式打开文件 # Print (F.read (5)) #可读 # f.write (' hello ') # print ('------') # print (F.read ()) # f = open (' Small Mountains 2 ', ' w+ ') #以写读模式打开文件 # Print (F.read (5)) #什么都没有 because the text is formatted first # f.write (' Hello Alex ') # print (F.read ()) #还是read不到 # F.seek (0) # Print (F.read ()) #w + with A + is the difference between starting to overwrite the entire file # OK, the point is, I want to add a line after the third line of text: ' Hello Yue Fei! ' # Some classmates said, didn't you make any changes in the front? Big Brother, just changed the content after print, now is to modify the file!!! # f = open (' Small Mountains 2 ', ' r+ ') #以写读模式打开文件 # f.readline () # f.readline () # f.readline () # Print (F.tell ()) # f.write (' Hello Yue Fei ') # F.clo SE () # and think differently, no matter! What about file modifications? # f_read = Open (' Small Mountains ', ' R ') #以写读模式打开文件 # f_write = open (' Small mountains _back ', ' W ') #以写读模式打开文件 # count=0# For F_read: # if count==3: # f_write.write (' Hello, Yue fei \ n ') # # Else: # F_write.write (line) # Another-line: # if count==3: # # line= ' Hello, Yue Fei 2\n ' # f_write.write (line) # count+=1# #二进制模式 # f = open (' Small Mountains 2 ', ' WB ') #以二进制的形式读文件 # # f = open (' Small Mountains 2 ', ' WB') #以二进制的形式写文件 # f.write (' Hello alvin! '). Encode ()) #b ' Hello alvin! ' is a binary format data, just for viewing, not shown in 010101 form
Note 1: Either Py2 or PY3, you can replace the equivalent byte in r+ mode, but it doesn't make any sense!
Note 2: There are students here will use ReadLines to get the content list, and then through the index to modify the corresponding content, and finally the list to re-write the file.
There is a big problem with this approach, and if the data is large, your memory will be overwhelmed, and our approach can optimize the process through iterators.
Supplement: RB mode and Seek
In the Py2:
#昨夜寒蛩不住鸣. F = open (' Test ', ' R ',) #以写读模式打开文件f. Read (3) # F.seek (3) # Print F.read (3) # night # F.seek (3,1) # Print F.read (3) # Cold # f.se Ek ( -4,2) # Print F.read (3) # Naruto
In the Py3:
# test: The Cold family Meconematidae from last night. F = open (' Test ', ' RB ',) #以写读模式打开文件f. Read (3) # F.seek (3) # Print (F.read (3)) # B ' \xe5\xa4\x9c ' # F.seek (3,1) # p Rint (F.read (3)) # B ' \xe5\xaf\x92 ' # F.seek ( -4,2) # Print (F.read (3)) # b ' \xe9\xb8\xa3 ' #总结: In Py3, if you want character data, that's for viewing, Then use R mode, so that the data I f.read is a decode # Unicode data, but if this data I do not need to see, but only for transmission, such as file upload, then I do not need to decode# Direct transmission bytes is good, So this time use RB mode. # in Py3, there is a strict line between bytes and Unicode, such as seek usage, in Py2 and Py3 is a byte seek,# but in py3 you have to declare the type of F is RB, It is not allowed to blur again. #建议: In the future to read and write files directly with the RB mode, need to decode when the display to decode.
4. With statement
To avoid forgetting to close a file after opening it, you can manage the context by:
With open (' Log ', ' R ') as F: Pass
This way, when the with code block finishes executing, the internal automatically shuts down and frees the file resource.
After Python 2.7, with also supports the management of multiple file contexts simultaneously, namely:
With open (' Log1 ') as Obj1, open (' log2 ') as Obj2: pass2