Free Ebook cover Python course with Lambda and API Gateway for backend development

Python course with Lambda and API Gateway for backend development

5

(1)

142 pages

File manipulation in Python

Capítulo 35

Estimated reading time: 3 minutes

Audio Icon

Listen in audio

0:00 / 0:00

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:

Continue in our app.

You can listen to the audiobook with the screen off, receive a free certificate for this course, and also have access to 5,000 other free online courses.

Or continue reading below...
Download App

Download the app

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.

In Python, the file opening mode 'x' is used to create a new file. If the file already exists, it will return an error. This is useful when you want to ensure that you do not accidentally overwrite an existing file.

Next chapter

Exception Handling in Python

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