This article is participating in Python Theme Month. See the link to the event for more details

Retrospective review

We learned about file closing last time in Python file closing Streams. This time we’ll learn more about file operations.

Before we learn, let’s review the Python file operations in three steps:

  • Create the file object and open the file
  • Perform operations such as reading and writing files
  • After the file operation, close the file

Also, in our brief analysis of Python file management, we learned that files are divided into text files and binary files

In this episode, we’re going to learn how to read, add, and delete files for fun.

So before we get to that, just to review, open file mode.

model role
r Open files with the default read-only permission
r+ After the file is opened, read from the beginning
rb The opened binary file has only the read-only permission
rb+ The open binary file has read and write permission
w Open file with read-only permission (will empty the original contents of the file)
w+ Open file with read/write permission (will empty the original file content)
wb The open binary file has the write – only permission
wb+ The open binary file has read and write permission
a Open file and append new content to existing content
a+ New content is added to the original content of the opened file, and the file has read and write permission
ab Open binaries append new content to existing content
ab+ The opened binary file has new content appened to the original content and has read and write permissions

Now that we have learned the open file mode, we can call the open() method to open our file and proceed from there

Note: we have called the open function to open the file. When we are done with the file, we should get into the good habit of closing the file

So let’s start our formal study today

1. Read and write text files

We create a.txt in the computer directory as

1.1 Reading text files

Open file mode with read is R,r+,w+,a+

There are generally three methods for reading files:

  1. read([size])

    • The size characters are read from the file and returned as the result, or the entire file if there is no size argument.
    • An empty string is returned when the file is read to the end
with open("a.txt") as f:
    f.read(3)
    
Copy the code

  1. readline()

    Read a line of content as a result. At the end of the file read, an empty string is returned

F = open(" a.t_t ") # open(" a.t_t ")Copy the code

  1. readlines()

    In a text file, each line is stored as a string in a list and that list is returned

f = open("a.txt",'rb')
str = f.readlines()
print(str)
f.close()
Copy the code

1.2 Text files are written

When we write to a text file, we open the file with four write modes: W, A,w+,a+

There are two ways to write text files:

  1. write()

    Writes specified contents to a file

When we write, when we open file mode A, we append the new write to the contents of the file

F = open (" a.t xt ", 'a') f.w rite (" write a line of new data \ n ") f. lose ()Copy the code

If the file is opened in W mode, the original content will be emptied and the new content will be written

F = open (" a.t xt, 'w') f.w rite (" writing fou the new data ") f. lose ()Copy the code

  1. writelines()

    You can write a list of strings to a file

    Let’s look at a Writelines method of chestnuts

F = open (' a.t xt ', 'r') n = open (' b.t xt ', 'w +') # b.t xt file is empty n.w ritelines (f.r eadlines (), n.c lose () f. lose ()Copy the code

Note: Write functions only have write() and writelines() functions, and there is no function named writeline.

2. Read and write binary files

The processing flow of binary files is the same as that of text files.

The only difference is that to open the binary, you need to add mode B

The main steps are as follows:

  1. To open a binary file, for example: open(” xx.jpg “,”rb”)
  2. Create file Objects
  3. Perform write and read operations
  4. Closing binaries

Let’s implement a copy a picture operation to practice reading and writing binary files

with open("BQ.jpg","rb") as f:
    with open("BQ_copy.jpg","wb") as w:
        for line in f.readlines():
            w.write(line)
print("copy end")
Copy the code

conclusion

In this installment, we learn and practice in detail the operation of reading and writing files. The mode and difference of opening a file before operating on it.

In the follow-up better operation of the document, to lay a solid foundation.

The above is the content of this issue, welcome the big guys to guide the point of attention, see next ~