Details about file operations in Python,
1. objects must be called, such as values, strings, lists, tuples, dictionaries, and even files. Everything in Python is an object.
str1 = 'hello' str2 = 'world' str3 = ' '.join([str1,str2]) print(str3)
2. Three basic file operation modes: r (only-read), w (only-write), and a (append)
Procedure for file operations:
First, create a file object.
Second, call the file method for operations.
Third, do not forget to close the file. (When the file is not closed, the content will be stored in the cache. Although Python will automatically read the content to the disk at the end, it should be used to close the file just in case)
File file1
A faded photo seems to give me a little bit of nostalgia. The hot noodle shop sold by grandpa at the end of the alley is filled with the old backyards. stray cats are sleeping and shaking on the swing. The sunset shines on his eyes. The postcard sent by the deskmate, lie quietly in the desk.
(1) r mode
In read-only mode, an error is reported when writing content.
F = open ('file1', 'R') f_read = f. read () # read is read by character. read can specify the parameter and set the number of characters to be read. Whether an English letter or a Chinese character is a single character. Print (f_read) f. close ()
F = open ('file1', 'R') f_read = f. readline () # readline can only read the first line of code. The principle is to stop reading the first line break. Print (f_read) f. close ()
F = open ('file1', 'R') f_read = f. readlines () # readlines will output the content in the form of a list. Print (f_read) f. close ()
F = open ('file1', 'R') for line in f. readlines () # Use the for loop to output the content by string. Print (line) # output a line of content to output a blank line, with a line of content containing a line of space... because each line of content in the file is followed by a line break, and the print () Statement itself can wrap. If you do not want to output empty lines, you need to use the following statement: print (line. strip () f. close ()
(2) w Mode
Before the operation, all content in the file will be cleared. For example, if 'Hello world' is written to file1, after the program is executed, only 'Hello world' is left in file1'
F = open ('file1', 'w', encoding = 'utf8') # because the default encoding method of Python3 is Unicode, you need to call utf8 when writing files, the file is saved in utf8 mode. In this case, pycharm (the default encoding method is utf8) can be read correctly. When the file is read, the file is in utf8 format, and pycharm is also utf8, so you do not need to call it. F_w = f. write ('Hello World') print (f_w) # interestingly, 'Hello world' is not printed here. Only the number of characters written to f. close () are printed ()
(3) a Mode
Unlike w mode, a mode does not clear the original content, but moves the cursor to the last position of the content to continue writing new content. For example, append 'Hello world' at the end'
F = open ('file1', 'A') f_a = f. write ('Hello World') print (f_a) # The number of written characters is still printed. f. close ()
Print the file and add the 'helloworld' output after 'Stray cats sleep and shake the swing '.
In the r mode, we usefor
Loop andreadlines()
Output file content. The principle of this output content is: open the file, read all the content into the memory, and then print the input. When the file is large, this reading method is unreliable, it may even crash the machine. We need to close the file in time, as shown below:
F = open ('file', 'R') data = f. readlines () # close the file in time. close () num = 0for I in data: num + = 1 if num = 5: I = ''. join ([I. strip (), 'Hello world']) # Do not splice print (I. strip () f. close ()
For big data files, use the following method:
Num = 0f. close () # Do not close the file too early. Otherwise, the program cannot identify the operation handle. f = open ('file', 'R') for I in f: # for internally converts f into an iterator and uses a row to take a row. Num + = 1 if num = 5: I = ''. join ([I. strip (), 'Hello world']) print (I. strip () f. close ()
3. tell and seek
Tell: query the cursor position in the file
Seek: cursor Positioning
F = open ('file', 'R') print (f. tell () # The cursor is at the starting position by default. seek (10) # position the cursor after 10th characters print (f. tell () # output 10f. close () ---------------------- f = open ('file', 'w') print (f. tell () # first clear the content, and the cursor returns to the 0 position f. seek (10) print (f. tell () f. close () ---------------------- f = open ('file', 'A') print (f. tell () # The cursor is at the last position by default. write ('Hello World') print (f. tell () #9 characters behind the cursor, still at the last position f. close ()
4. flush synchronize data from cache to disk
Example to implement the progress bar Function
Import sys, time # import sys and time modules for I in range (40): sys. stdout. write ('*') sys. stdout. flush () # flush is equivalent to taking a photo, taking a picture and flushing a time. the code below sleep (0.2) can also implement the same function import time for I in range (40): print ('*', end = '', flush = True) # flush parameter time in print. sleep (0.2)
5. truncate Truncation
It cannot be executed in r mode,
In w mode, all data has been cleared. Usetruncate
No meaning,
In a mode, content at the specified position is truncated.
F = open ('file', 'A') f. truncate (6) # Only 6 bytes of content (6 English characters or three Chinese characters) are displayed, and the subsequent content is cleared.
6. cursor position summary
A Chinese character contains two bytes and four methods are involved in the cursor position:read
,tell
,seek
,truncate
.
# -------------------------- Cursor summary head --------------------------------------- f = open ('file', 'R') print (f. read (6) #6 Characters print (f. tell () # Location 12 bytes, one Chinese character two bytes f. close () f = open ('file', 'R') f. seek (6) #6 bytes print (f. tell () f. close () f = open ('file', 'A') print (f. tell () # The cursor is at the last position by default. write ('Hello World') print (f. tell () #9 bytes after the cursor, one Chinese character two bytes, still at the last position 182 --> 191f. close () f = open ('file', 'A', encoding = 'utf-8') print (f. truncate (6) # cursor positioning required Location, so it is also a byte. Only 6 bytes of content (6 English letters or three Chinese characters, one Chinese Character and two bytes) are displayed, and the subsequent content is cleared. F. close () # ----------------------------- cursor summary end ---------------------------------
7. Three other modes: r +, w +, and a +
R +: read/write mode. The cursor is at the starting position by default. When writing data, the cursor automatically moves to the end.
W +: Write-Read mode. The original content is cleared and then written.
A +: append read mode. The cursor is at the last position by default and can be read directly.
F = open ('file', 'A') print (f. tell () # End 207 position f. close () f = open ('file', 'r + ') print (f. tell () #0 position print (f. readline () # read the first line f. write ('goat gazelle ') # move the cursor to the 207 position at the end and write the print (f. tell () #213 (position f. seek (0) # move the cursor to 0 position print (f. readline () # read the first line f. close ()
8. Modify file content
Idea: Due to the relationship between the data storage mechanism, we can only read the content in file 1 and put it in file 2 after modification.
F2 = open ('file2', 'w', encoding = 'utf8') # utf8f1 = open ('file', 'R') must be added when writing data ') num = 0for line in f1: # iterator num + = 1 if num = 5: line = ''. join ([line. strip (), 'yangxiaoling \ n']) # The character string is operated on f2.write (line) f1.close () f2.close ()
9. with statement
You can operate on multiple files at the same time.with
When the code block is executed, the file is automatically closed to release memory resources.f.close()
In the following example:with
.
Usewith
Statement rewriting code in 8
Num = 0 with open ('file', 'R') as f1, open ('file2', 'w', encoding = 'utf8') as f2: for line in f1: num + = 1 if num = 5: line = ''. join ([line. strip (), 'yangxiaorang']) f2.write (line)
10. Summary
The above is all the content of this article, hoping to help you. If you have any questions, leave a message.