Location>code7788 >text

18 How does Python manipulate files?

Popularity:472 ℃/2024-09-10 09:57:52

This is the 18th in a series of Python tutorials; for more, visit my Python collection!

1 Open file

It is common to use the built-in open(file path, mode, encoding="utf-8")function.

  • File path: can be a relative or absolute path.
  • Mode: (optional) determines how the file will be handled once it is opened.
  • encoding: (optional) encoding method.

Common patterns are:

  • 'r' (default): read-only mode, raises FileNotFoundError if the file does not exist.
  • 'w': write mode, if the file exists it will clear the content and write again, if the file does not exist it will create a new file.
  • 'a': append mode, append content at the end of the file, or create a new file if the file does not exist.
  • 'b': binary mode for processing binary files (e.g. images, audio, etc.).
  • '+': update mode for simultaneous read and write operations.

It is possible to use these patterns in combination, for example:

  • 'rb': read the file in binary mode.
  • 'wb': write to file in binary mode.
  • 'ab': append content to file in binary mode.
  • 'r+': read/write mode, can read and write files.
  • 'w+': write and read mode, write first then read.
  • 'a+': append and read mode, append first and then read.

2 File reading

in the event thatopen()Successful execution of the function returns a file object. Subsequent read or write operations can be performed on this object.

f = open('./', 'r', encoding='utf-8')

The file object has aread()method, which reads everything in the file at once and returns it in string format.

Example:

file = open('', 'r', encoding="utf-8")
print(())

Attention:

  • If theread()Calling it again after that will return null, because the program will record where the file was read, and the first time theread()When you have read to the end of the file, the secondread()There is no content after that.
  • Large files are also not suitable for useread(), because it will read all the contents of the file at once and may crowd the memory.

It says that large files are not suitable forread()So, is there any other solution to replace it? Of course there is, the solution is to read only part of the content at once, for example:

  • do sth (for sb)read()Pass a numeric parameter such asread(1024), which indicates how many bytes are read at a time, and the next time you call theread(1024)When it does, it continues to read from the last end position.
  • utilizationreadline()This method will only read one line of content at a time, based on line breaks to determine the end of the line, and line breaks will also be read as part of the content.

The two above can be pairedwhileloop to use, plus areadlines()method, which returns all the rows at once, forming a list of strings, usually paired with theforRecycling.

3 File Write

call (programming)open()function when passing the second parameterwmaybeaThe file write operation can then be performed. As a note here, if the second argument isrIf the file does not exist, it will reportFileNotFoundErrorError, butwmaybeaThere will be no errors, it will automatically create a file.

After opening or creating a file you can call the file object'swrite()method to perform a write operation now.

Example:

with open('', 'w', encoding="utf-8") as file:
    ("hello ")
    ("python")

Content:

hello python

take note ofwrite()method does not automatically break lines, you need to manually add line breaks, such as changing the code to("hello\n"), and it will become:

hello
python

If we use thewmode, the file can only be written to but not read, if we want to read before writing, we can use ther+paradigm

4 Closing the file

After the file operation is complete, the file object needs to call aclose()method closes the file to release resources.

After each file operation should be closed, but there may be careless forget to close, how to do? We can do this by calling theopen()function to open a file using thewithkeyword, and then use theasSpecify the file to read into, so that thewithThe file is automatically closed after the code block is executed, example:

# utilization with statement to read the file
with open('', 'r', encoding='utf-8') as file:
    for line in ():
        print(())