Python -- File operations (manipulating files)

File operations include: read, write, modify

Multiple operations for files:

 1 # Read all the contents of the file
 2 data = open("yesteday.txt", encoding="utf-8") .read()
 3 print(data)
 4 
 5 '''  f:File handle (file name, character set, size, starting position on hard disk containing this file) '''
 6 
 7 # 'a'=append Append
 8 f = open("yesteday2.txt", 'a', encoding="utf-8")
 9 f.write("qwerQWER1111\n") #Add content at the end of the file
10 f.close()
11 
12 # 'w'=write Write, overwrite previous content
13 f = open("yesteday2.txt", 'w', encoding="utf-8")
14 f.write("AAAADDDDD\n")
15 f.write("CCCCVVVVV\n")
16 f.close()
17 
18 #'r'=read read-only
19 f = open("yesteday2.txt", 'r', encoding="utf-8")
20 print(f.read())
21 f.close()
22 
23 # 'r+' = r+a  Read and append at the end
24 f = open("yesteday.txt", 'r+', encoding='utf-8')
25 print(f.readline())
26 print(f.tell())
27 f.write("---nihao---\n")
28 print(f.readline()) #No output results because r+Writing is done at the end, so the cursor reaches the end and you can't read anything.
29 print(f.tell()) #tell Count by character,Return cursor position
30 f.seek(0) #Return to a location
31 print(f.read())
32 f.close()
33 
34 # 'w+' = w+r Write and Read,Write or only append at the end of the file
35 f = open("yesteday.txt", 'w+', encoding='utf-8')
36 print(f.readline()) #Unable to read content,because w+Will create a new file,Empty the contents of the original file
37 f.write("---nihao---\n") #Writing is done at the end, so the cursor reaches the end and you can't read anything.
38 f.write("---oh,god---\n")
39 print(f.tell())
40 f.seek(3)
41 print(f.tell())
42 print(f.readline()) #When the cursor is not at the beginning of a line, readline Reads after the cursor
43 print(f.tell())
44 f.write("Write after the first line") #Writing is done at the end, and even by adjusting the position of the cursor, this line cannot be written after the first line
45 print(f.tell())
46 f.seek(0)
47 print(f.read())
48 f.close()
49 
50 # 'a+'Append Read
51 f = open("yesteday.txt", 'a+', encoding='utf-8')
52 print(f.read()) #Unable to read,because a+Default cursor at end
53 f.write("---nihao---\n")
54 print(f.tell()) #tell Count by character,Return cursor position
55 f.seek(0) #Return to a location
56 print(f.read())
57 f.close()
58 
59 # 'rb' = Read files in binary format
60 f = open("yesteday.txt", 'rb') #Cannot add encoding Format of
61 print(f.read())
62 f.seek(0) #Return to a location
63 print(f.read())
64 f.seek(0) #Return to a location
65 print(f.read())
66 f.seek(0) #Return to a location
67 print(f.readline()) #readline Read a line
68 f.close()
69 
70 # 'wb' = Write files in binary format,Will empty the contents of the original file
71 f = open("yesteday.txt", 'wb') #Use wb String needs to be binary when writing
72 f.write("hello binary\n".encode()) #take hello binary Write to file after changing to binary format
73 f.write("hello binary\n".encode())
74 f.close()
75 
76 # 'ab' = Append Write Files in Binary Format
77 f = open("yesteday.txt", 'ab')
78 f.write("hello binary\n".encode())
79 f.close()

Other methods for files:

 1 # f = open("yesteday2.txt", 'a+', encoding="utf-8")
 2 # print(f.tell()) #The cursor is at the end of the file
 3 # print(f.read(5)) #Unable to read content
 4 # print(f.tell()) #tell counts by character
 5 # f.seek(3)  #Return to a location
 6 # print(f.readline()) #When seek goes back to the middle of a line, the next time it reads a line, it cut s out the front part and reads the back part
 7 # f.seek(3)
 8 # print(f.tell()) #Get where the file was read
 9 # print(f.encoding) #Returns the encoding format of the file handle
10 # print(f.fileno()) #Return Number--Operating System Interface
11 # print(f.seekable()) #Can you move the cursor back and return True
12 # print(f.readable()) #Determine if the file is readable
13 # print(f.writable()) #Determine whether a file is writable
14 # f.write("1111222333\n")
15 # f.write("1111222333\n") #Write operations start with a memory cache, not directly written to the hard disk. When the cache reaches a value, it is also written to the hard disk
16 # f.flush() # Forced Refresh - Writes the contents of the cache to the hard disk
17 # f.truncate(10) #Truncate, truncate the back part from the specified position, empty it if you do not write the default truncate from scratch, and move the cursor without seek
18 # f.close() #Close open files
19 # print(f.closed) #Determine if it is closed

Examples of file reading:

 1 # Read Five Lines
 2 f = open("yesteday2.txt", 'r', encoding="utf-8")
 3 for i in range(5):
 4     data = f.readline()
 5     print(data)
 6 f.close()
 7 
 8 # Read 5 Characters
 9 f = open("yesteday2.txt")
10 print(f.tell())
11 print(f.read(5))
12 f.close()
13 
14 # Print everything except the third line
15 # enumerate() Function to use a traversable data object(Such as a list, tuple, or string)Combines a series of indexes, listing both data and data subscripts, commonly used in for In a cycle
16 f = open("yesteday2.txt", 'r', encoding="utf-8")
17 for index,line in enumerate(f.readlines()):
18     if index == 3:
19         print("------")
20         continue
21     print(line.strip()) # strip() Method to remove the character specified at the beginning and end of a string (default is space or line break) or a character sequence
22 f.close()
23 
24 # Efficient. Read one line to add one line to memory. Reading the next line will overwrite the previous line in memory
25 f = open("yesteday2.txt", 'r', encoding="utf-8")
26 count = 0
27 for line in f:
28     if count == 3:
29         count += 1
30         print("----------3-----------")
31         continue
32     print(line)
33     count += 1
34 f.close()

With the above placement, it is not possible to actually complete the modification of the file because writing to the file always ends up at the end of the file or overwrites the source file

The contents of the file can be modified in the following ways:

>>> testfile.txt
 Like a movie forgiving a tragic box office failure
 I wander around the street with my head full and my mind in exile
 Turn off the phone, remove the seat and sit by the road
 Just as a beggar doesn't need an image
 Ten thousand lights led the starlight to spell out the night
 Brilliant desire flooded every frail part of the street
 Play a leaderboard in a square speaker
 Top Songs Like Background
 That's not a song That's a lonely song
 The logic of this white horse is rarely concordant
 Singing how many twists and turns in what story
 Several people in the bustle know how many people know it
 That's not a song That's my song
 My joy or grief at that time could not be remembered
 Songs of Southern Regions and Northern Rules Destroying the Entertainment
 Several people know how many people know
 Pressed off in panic
 1 f = open("testfile", "r", encoding="utf-8")
 2 f_new = open("testfile2", "w", encoding="utf-8")
 3 
 4 for line in f:
 5     if "Several people recognized it" in line:
 6         # '1'Modify the first match on behalf of this line only
 7         line = line.replace("Several people recognized it", "who(shui)Human perception", 1)
 8     f_new.write(line)
 9 f.close()
10 f_new.close()

To prevent you from forgetting to close the file after a file operation, you can use the with syntax:

 1 #To avoid forgetting to close after opening a file, you can manage the context by
 2 with open("testfile", "r", encoding="utf-8") as f:
 3     for line in f:
 4         print(line)
 5 
 6 #In this way, when with When the code block is executed, resources are automatically closed and released internally
 7 #stay py2.7 After that, with It also supports the management of multiple files'contexts simultaneously, i.e.
 8 with open("testfile", "r", encoding="utf-8") as f1,\
 9         open("testfile2", "w", encoding="utf-8") as f2:
10     print(f1.readline())
11     f2.writable()

Tags: Python encoding

Posted on Sat, 23 May 2020 10:00:15 -0700 by mikeyinsane