File manipulation is an essential part of any programming application, and Python offers several functions and methods to perform this task effectively. File manipulation allows you to read, write, update and delete files. In this chapter, we'll explore how Python manipulates files.

Opening Files

Before reading or writing to a file, we first need to open it. Python has a built-in function called open() for this. The open() function has two parameters: the file name and the mode.

There are four methods (modes) that can be used to open files:

  • "r" - Read: This is the default value. Opens the file for reading, returns an error if the file does not exist.
  • "a" - Append: Opens the file to append any data at the end of the file without truncating the original content. Creates the file if it does not exist.
  • "w" - Write: Opens the file for writing. Creates the file if it does not exist. If the file exists, truncates the file.
  • "x" - Create: Creates the file, returns an error if the file exists.

File Reading

After opening a file, we can read its contents with the read() method. For example:

file = open("file.txt", "r")
print(file.read())

In addition, we can read parts of a file at a time, specifying how many characters to read, as in this example:

file = open("file.txt", "r")
print(file.read(5))

We can also read the file line by line using the readline() method.

Writing in Files

We can write to a file using "w" or "a" mode. If the file does not exist, "w" mode will create it. However, be careful because if the file already exists, "w" mode will overwrite it. On the other hand, "a" mode will append the text to the end of the existing file.

file = open("file.txt", "w")
file.write("This is new content")
file.close()

Remember to always close the file after you finish writing. This is important because it ensures that resources are released and changes are saved.

Close Files

When we are finished with a file, we must always close it. This is done with the close() method.

file = open("file.txt", "r")
print(file.read())
file.close()

Working with Files Using with

A better way to work with files is to use the with keyword. It creates a context in which the file is opened and then automatically closes the file when the block of code inside the with exits. This is useful because it ensures that the file closes correctly even if an error occurs.

with open("file.txt", "r") as file:
    print(file.read())

Manipulating files is a common task in many Python programs, whether to read configurations, write logs, store data, or any other reason. Python makes file manipulation a simple and straightforward task.

Now answer the exercise about the content:

Which of the following file opening modes in Python creates a new file and returns an error if the file already exists?

You are right! Congratulations, now go to the next page

You missed! Try again.

Article image Exception Handling in Python 36

Next page of the Free Ebook:

Exception Handling in Python

Estimated reading time: 3 minutes

Download the app to earn free Certification and listen to the courses in the background, even with the screen off.

+ 9 million
students

Free and Valid
Certificate

60 thousand free
exercises

4.8/5 rating in
app stores

Free courses in
video and ebooks