Python

Python Files

Python Files

The programming language of Python allows files management. This means that through code, the system can perform various functions onto files, such as cerate, open, read, write, close, and delete.

The main function for managing files is “open()“, and everything operates through it. This means that in order to read or update a file, it must be opened first.

It is also a good convention to always close the file after performing any operation. The function “close()” can do this.

The following is an example of opening and closing a file.

# Open file
x = open("file.txt")

# Close file
x.close()
  • It is a good practice to store the function “open()” in a variable.
  • If the file is in the same directory as the Python script, the code requires only the name and the extension of the file.
  • In the case where the file is not in the same directory, the path must be included (e.g. \files\documents\xyz\file.txt)

Modes

By default, the function “open()” opens the file in reading mode.

There are four different ways to open a file. Each method specifies the mode.

  • r” refers to reading mode
  • w” refers to writing mode
  • a” refers to appending mode
  • x” refers to creating mode

The above represents the cases of:

  • If there is a need to only read a file, Python requires the reading mode (“r”).
  • If there is a need to write to a file, Python requires the writing mode (“w”).
  • If there is a need to append a file, Python requires the appending mode (“a”).
  • If there is a need to cerate a file, Python requires the creating mode (“x”).

The “open()” function declares all modes after the name and extension of the file.

# read mode
x = open("file.txt", "r")
x.close()

# write mode
x = open("file.txt", "w")
x.close()

# append mode
x = open("file.txt", "a")
x.close()

# create mode
x = open("file.txt", "x")
x.close()

The difference of write and append is that the former rewrites all content within the file and the latter only adds more content at the end. In other words, if there is any information in a file, write will delete everything inside, and then write the new data. Append on the other hand, will not delete anything, but write the new information at the end of the old one.


Next: Python Errors