This code snippet stores and updates a list that represents files in a folder:

Hi! If you want to learn how to work with files in Python, then this article is for you. Working with files is an important skill that every Python developer should learn, so let's get started.

In this article, you will learn:

  • How to open a file.
  • How to read a file.
  • How to create a file.
  • How to modify a file.
  • How to close a file.
  • How to open files for multiple operations.
  • How to work with file object methods.
  • How to delete files.
  • How to work with context managers and why they are useful.
  • How to handle exceptions that could be raised when you work with files.
  • and more!

Let's begin! ✨

🔹 Working with Files: Basic Syntax

One of the most important functions that you will need to use as you work with files in Python is

f = open("data/names.txt", "a")
print(f.mode) # Output: "a"
9, a built-in function that opens a file and allows your program to use it and work with it.

This is the basic syntax:

This code snippet stores and updates a list that represents files in a folder:

💡 Tip: These are the two most commonly used arguments to call this function. There are six additional optional arguments. To learn more about them, please read in the documentation.

First Parameter: File

The first parameter of the

f = open("data/names.txt")
print(f.read())
0 function is
f = open("data/names.txt")
print(f.read())
1, the absolute or relative path to the file that you are trying to work with.

We usually use a relative path, which indicates where the file is located relative to the location of the script (Python file) that is calling the

f = open("data/names.txt")
print(f.read())
0 function.

For example, the path in this function call:

open("names.txt") # The relative path is "names.txt"

Only contains the name of the file. This can be used when the file that you are trying to open is in the same directory or folder as the Python script, like this:

This code snippet stores and updates a list that represents files in a folder:

But if the file is within a nested folder, like this:

This code snippet stores and updates a list that represents files in a folder:
The names.txt file is in the "data" folder

Then we need to use a specific path to tell the function that the file is within another folder.

In this example, this would be the path:

open("data/names.txt")

Notice that we are writing

f = open("data/names.txt")
print(f.read())
3 first (the name of the folder followed by a
f = open("data/names.txt")
print(f.read())
4) and then
f = open("data/names.txt")
print(f.read())
5 (the name of the file with the extension).

💡 Tip: The three letters

f = open("data/names.txt")
print(f.read())
6 that follow the dot in
f = open("data/names.txt")
print(f.read())
5 is the "extension" of the file, or its type. In this case,
f = open("data/names.txt")
print(f.read())
6 indicates that it's a text file.

Second Parameter: Mode

The second parameter of the

f = open("data/names.txt")
print(f.read())
0 function is the
Nora
Gino
Timmy
William
0, a string with one character. That single character basically tells Python what you are planning to do with the file in your program.

Modes available are:

  • Read (
    Nora
    Gino
    Timmy
    William
    1).
  • Append (
    Nora
    Gino
    Timmy
    William
    2)
  • Write (
    Nora
    Gino
    Timmy
    William
    3)
  • Create (
    Nora
    Gino
    Timmy
    William
    4)

You can also choose to open the file in:

  • Text mode (
    Nora
    Gino
    Timmy
    William
    5)
  • Binary mode (
    Nora
    Gino
    Timmy
    William
    6)

To use text or binary mode, you would need to add these characters to the main mode. For example:

Nora
Gino
Timmy
William
7 means writing in binary mode.

💡 Tip: The default modes are read (

Nora
Gino
Timmy
William
1) and text (
Nora
Gino
Timmy
William
5), which means "open for reading text" (
print(type(f.read()))

# Output
0), so you don't need to specify them in
f = open("data/names.txt")
print(f.read())
0 if you want to use them because they are assigned by default. You can simply write
print(type(f.read()))

# Output
2.

Why Modes?

It really makes sense for Python to grant only certain permissions based what you are planning to do with the file, right? Why should Python allow your program to do more than necessary? This is basically why modes exist.

Think about it — allowing a program to do more than necessary can problematic. For example, if you only need to read the content of a file, it can be dangerous to allow your program to modify it unexpectedly, which could potentially introduce bugs.

🔸 How to Read a File

Now that you know more about the arguments that the

f = open("data/names.txt", "a")
print(f.mode) # Output: "a"
9 function takes, let's see how you can open a file and store it in a variable to use it in your program.

This is the basic syntax:

This code snippet stores and updates a list that represents files in a folder:

We are simply assigning the value returned to a variable. For example:

names_file = open("data/names.txt", "r")

I know you might be asking: what type of value is returned by

f = open("data/names.txt", "a")
print(f.mode) # Output: "a"
9?

Well, a file object.

Let's talk a little bit about them.

File Objects

According to the , a file object is:

An object exposing a file-oriented API (with methods such as read() or write()) to an underlying resource.

This is basically telling us that a file object is an object that lets us work and interact with existing files in our Python program.

File objects have attributes, such as:

  • name: the name of the file.
  • closed:
    print(type(f.read()))
    
    # Output
    
    5 if the file is closed.
    print(type(f.read()))
    
    # Output
    
    6 otherwise.
  • mode: the mode used to open the file.
This code snippet stores and updates a list that represents files in a folder:

For example:

f = open("data/names.txt", "a")
print(f.mode) # Output: "a"

Now let's see how you can access the content of a file through a file object.

Methods to Read a File

For us to be able to work file objects, we need to have a way to "interact" with them in our program and that is exactly what methods do. Let's see some of them.

Read()

The first method that you need to learn about is

print(type(f.read()))

# Output
7, which returns the entire content of the file as a string.

This code snippet stores and updates a list that represents files in a folder:

Here we have an example:

f = open("data/names.txt")
print(f.read())

The output is:

Nora
Gino
Timmy
William

You can use the

print(type(f.read()))

# Output
8 function to confirm that the value returned by
print(type(f.read()))

# Output
9 is a string:

print(type(f.read()))

# Output

Yes, it's a string!

In this case, the entire file was printed because we did not specify a maximum number of bytes, but we can do this as well.

Here we have an example:

f = open("data/names.txt")
print(f.read(3))

The value returned is limited to this number of bytes:

Nor

❗️Important: You need to close a file after the task has been completed to free the resources associated to the file. To do this, you need to call the

f = open("data/names.txt")
print(f.read(3))
0 method, like this:

This code snippet stores and updates a list that represents files in a folder:

Readline() vs. Readlines()

You can read a file line by line with these two methods. They are slightly different, so let's see them in detail.

f = open("data/names.txt")
print(f.read(3))
1 reads one line of the file until it reaches the end of that line. A trailing newline character (
f = open("data/names.txt")
print(f.read(3))
2) is kept in the string.

💡 Tip: Optionally, you can pass the size, the maximum number of characters that you want to include in the resulting string.

This code snippet stores and updates a list that represents files in a folder:

For example:

f = open("data/names.txt")
print(f.readline())
f.close()

The output is:

open("data/names.txt")
0

This is the first line of the file.

In contrast,

f = open("data/names.txt")
print(f.read(3))
3 returns a list with all the lines of the file as individual elements (strings). This is the syntax:

This code snippet stores and updates a list that represents files in a folder:

For example:

open("data/names.txt")
1

The output is:

open("data/names.txt")
2

Notice that there is a

f = open("data/names.txt")
print(f.read(3))
2 (newline character) at the end of each string, except the last one.

💡 Tip: You can get the same list with

f = open("data/names.txt")
print(f.read(3))
5.

You can work with this list in your program by assigning it to a variable or using it in a loop:

open("data/names.txt")
3

We can also iterate over

f = open("data/names.txt")
print(f.read(3))
6 directly (the file object) in a loop:

open("data/names.txt")
4

Those are the main methods used to read file objects. Now let's see how you can create files.

🔹 How to Create a File

If you need to create a file "dynamically" using Python, you can do it with the

Nora
Gino
Timmy
William
4 mode.

Let's see how. This is the basic syntax:

This code snippet stores and updates a list that represents files in a folder:

Here's an example. This is my current working directory:

This code snippet stores and updates a list that represents files in a folder:

If I run this line of code:

open("data/names.txt")
5

A new file with that name is created:

This code snippet stores and updates a list that represents files in a folder:

With this mode, you can create a file and then write to it dynamically using methods that you will learn in just a few moments.

💡 Tip: The file will be initially empty until you modify it.

A curious thing is that if you try to run this line again and a file with that name already exists, you will see this error:

open("data/names.txt")
6

According to the , this exception (runtime error) is:

Raised when trying to create a file or directory which already exists.

Now that you know how to create a file, let's see how you can modify it.

🔸 How to Modify a File

To modify (write to) a file, you need to use the

f = open("data/names.txt")
print(f.read(3))
8 method. You have two ways to do it (append or write) based on the mode that you choose to open it with. Let's see them in detail.

Append

"Appending" means adding something to the end of another thing. The

Nora
Gino
Timmy
William
2 mode allows you to open a file to append some content to it.

For example, if we have this file:

This code snippet stores and updates a list that represents files in a folder:

And we want to add a new line to it, we can open it using the

Nor
0 mode (append) and then, call the
f = open("data/names.txt")
print(f.read(3))
8 method, passing the content that we want to append as argument.

This is the basic syntax to call the

f = open("data/names.txt")
print(f.read(3))
8 method:

This code snippet stores and updates a list that represents files in a folder:

Here's an example:

open("data/names.txt")
7

💡 Tip: Notice that I'm adding

f = open("data/names.txt")
print(f.read(3))
2 before the line to indicate that I want the new line to appear as a separate line, not as a continuation of the existing line.

This is the file now, after running the script:

This code snippet stores and updates a list that represents files in a folder:

💡 Tip: The new line might not be displayed in the file until

Nor
4 runs.

Write

Sometimes, you may want to delete the content of a file and replace it entirely with new content. You can do this with the

f = open("data/names.txt")
print(f.read(3))
8 method if you open the file with the
Nor
6 mode.

Here we have this text file:

This code snippet stores and updates a list that represents files in a folder:

If I run this script:

open("data/names.txt")
8

This is the result:

This code snippet stores and updates a list that represents files in a folder:

As you can see, opening a file with the

Nor
6 mode and then writing to it replaces the existing content.

💡 Tip: The

Nor
8 method returns the number of characters written.

If you want to write several lines at once, you can use the

Nor
9 method, which takes a list of strings. Each string represents a line to be added to the file.

Here's an example. This is the initial file:

This code snippet stores and updates a list that represents files in a folder:

If we run this script:

open("data/names.txt")
9

The lines are added to the end of the file:

This code snippet stores and updates a list that represents files in a folder:

Open File For Multiple Operations

Now you know how to create, read, and write to a file, but what if you want to do more than one thing in the same program? Let's see what happens if we try to do this with the modes that you have learned so far:

If you open a file in

Nora
Gino
Timmy
William
1 mode (read), and then try to write to it:

names_file = open("data/names.txt", "r")
0

You will get this error:

names_file = open("data/names.txt", "r")
1

Similarly, if you open a file in

Nora
Gino
Timmy
William
3 mode (write), and then try to read it:

names_file = open("data/names.txt", "r")
2

You will see this error:

names_file = open("data/names.txt", "r")
3

The same will occur with the

Nora
Gino
Timmy
William
2 (append) mode.

How can we solve this? To be able to read a file and perform another operation in the same program, you need to add the

f = open("data/names.txt")
print(f.readline())
f.close()
3 symbol to the mode, like this:

names_file = open("data/names.txt", "r")
4
names_file = open("data/names.txt", "r")
5
names_file = open("data/names.txt", "r")
6

Very useful, right? This is probably what you will use in your programs, but be sure to include only the modes that you need to avoid potential bugs.

Sometimes files are no longer needed. Let's see how you can delete files using Python.

🔹 How to Delete Files

To remove a file using Python, you need to import a module called

f = open("data/names.txt")
print(f.readline())
f.close()
4 which contains functions that interact with your operating system.

💡 Tip: A module is a Python file with related variables, functions, and classes.

Particularly, you need the

f = open("data/names.txt")
print(f.readline())
f.close()
5 function. This function takes the path to the file as argument and deletes the file automatically.

This code snippet stores and updates a list that represents files in a folder:

Let's see an example. We want to remove the file called

f = open("data/names.txt")
print(f.readline())
f.close()
6.

This code snippet stores and updates a list that represents files in a folder:

To do it, we write this code:

names_file = open("data/names.txt", "r")
7
  • The first line:
    f = open("data/names.txt")
    print(f.readline())
    f.close()
    7 is called an "import statement". This statement is written at the top of your file and it gives you access to the functions defined in the
    f = open("data/names.txt")
    print(f.readline())
    f.close()
    8 module.
  • The second line:
    f = open("data/names.txt")
    print(f.readline())
    f.close()
    9 removes the file specified.

💡 Tip: you can use an absolute or a relative path.

Now that you know how to delete files, let's see an interesting tool... Context Managers!

🔸 Meet Context Managers

Context Managers are Python constructs that will make your life much easier. By using them, you don't need to remember to close a file at the end of your program and you have access to the file in the particular part of the program that you choose.

Syntax

This is an example of a context manager used to work with files:

This code snippet stores and updates a list that represents files in a folder:

💡 Tip: The body of the context manager has to be indented, just like we indent loops, functions, and classes. If the code is not indented, it will not be considered part of the context manager.

When the body of the context manager has been completed, the file closes automatically.

names_file = open("data/names.txt", "r")
8

Example

Here's an example:

names_file = open("data/names.txt", "r")
9

This context manager opens the

f = open("data/names.txt")
print(f.read())
5 file for read/write operations and assigns that file object to the variable
f = open("data/names.txt")
print(f.read(3))
6. This variable is used in the body of the context manager to refer to the file object.

Trying to Read it Again

After the body has been completed, the file is automatically closed, so it can't be read without opening it again. But wait! We have a line that tries to read it again, right here below:

f = open("data/names.txt", "a")
print(f.mode) # Output: "a"
0

Let's see what happens:

f = open("data/names.txt", "a")
print(f.mode) # Output: "a"
1

This error is thrown because we are trying to read a closed file. Awesome, right? The context manager does all the heavy work for us, it is readable, and concise.

🔹 How to Handle Exceptions When Working With Files

When you're working with files, errors can occur. Sometimes you may not have the necessary permissions to modify or access a file, or a file might not even exist.

As a programmer, you need to foresee these circumstances and handle them in your program to avoid sudden crashes that could definitely affect the user experience.

Let's see some of the most common exceptions (runtime errors) that you might find when you work with files:

FileNotFoundError

According to the , this exception is:

Raised when a file or directory is requested but doesn’t exist.

For example, if the file that you're trying to open doesn't exist in your current working directory:

f = open("data/names.txt", "a")
print(f.mode) # Output: "a"
2

You will see this error:

f = open("data/names.txt", "a")
print(f.mode) # Output: "a"
3

Let's break this error down this line by line:

  • open("data/names.txt")
    02. This line tells you that the error was raised when the code on the file located in
    open("data/names.txt")
    03 was running. Specifically, when
    open("data/names.txt")
    04 was executed in
    open("data/names.txt")
    05.
  • open("data/names.txt")
    06. This is the line that caused the error.
  • open("data/names.txt")
    07 . This line says that a
    open("data/names.txt")
    08 exception was raised because the file or directory
    f = open("data/names.txt")
    print(f.read())
    5 doesn't exist.

💡 Tip: Python is very descriptive with the error messages, right? This is a huge advantage during the process of debugging.

PermissionError

This is another common exception when working with files. According to the , this exception is:

Raised when trying to run an operation without the adequate access rights - for example filesystem permissions.

This exception is raised when you are trying to read or modify a file that don't have permission to access. If you try to do so, you will see this error:

f = open("data/names.txt", "a")
print(f.mode) # Output: "a"
4

IsADirectoryError

According to the , this exception is:

Raised when a file operation is requested on a directory.

This particular exception is raised when you try to open or work on a directory instead of a file, so be really careful with the path that you pass as argument.

How to Handle Exceptions

To handle these exceptions, you can use a try/except statement. With this statement, you can "tell" your program what to do in case something unexpected happens.

This is the basic syntax:

f = open("data/names.txt", "a")
print(f.mode) # Output: "a"
5

Here you can see an example with

open("data/names.txt")
08:

f = open("data/names.txt", "a")
print(f.mode) # Output: "a"
6

This basically says:

  • Try to open the file
    f = open("data/names.txt")
    print(f.read())
    5.
  • If a
    open("data/names.txt")
    08 is thrown, don't crash! Simply print a descriptive statement for the user.

💡 Tip: You can choose how to handle the situation by writing the appropriate code in the

open("data/names.txt")
13 block. Perhaps you could create a new file if it doesn't exist already.

To close the file automatically after the task (regardless of whether an exception was raised or not in the

open("data/names.txt")
14 block) you can add the
open("data/names.txt")
15 block.

f = open("data/names.txt", "a")
print(f.mode) # Output: "a"
7

This is an example:

f = open("data/names.txt", "a")
print(f.mode) # Output: "a"
8

There are many ways to customize the try/except/finally statement and you can even add an

open("data/names.txt")
16 block to run a block of code only if no exceptions were raised in the
open("data/names.txt")
14 block.

💡 Tip: To learn more about exception handling in Python, you may like to read my article: "How to Handle Exceptions in Python: A Detailed Visual Introduction".

🔸 In Summary

  • You can create, read, write, and delete files using Python.
  • File objects have their own set of methods that you can use to work with them in your program.
  • Context Managers help you work with files and manage them by closing them automatically when a task has been completed.
  • Exception handling is key in Python. Common exceptions when you are working with files include
    open("data/names.txt")
    08,
    open("data/names.txt")
    19 and
    open("data/names.txt")
    20. They can be handled using try/except/else/finally.

I really hope you liked my article and found it helpful. Now you can work with files in your Python projects. Check out my online courses. Follow me on Twitter. ⭐️

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT


This code snippet stores and updates a list that represents files in a folder:
Estefania Cassingena Navone

Developer, technical writer, and content creator @freeCodeCamp. I run the freeCodeCamp.org Español YouTube channel.


If you read this far, tweet to the author to show them you care. Tweet a thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Which types of data are stored on a computer using bits?

All data inside of modern computers are stored as a series of ones and zeros — we call this binary data. The ones and zeros are called binary digits (or “bits” for short). In modern computers, data are stored in small blocks of eight bits called a “byte”.

What is the maximum times the computer will execute the code inside the repeat loop?

Part 2: What is the maximum times the computer will execute the code inside the REPEAT loop? The computer wouldn't execute the code more than 5 times.

How can Ada persuade her classmate to start organizing their code into procedures choose 1 answer?

How can Ada persuade her classmate to start organizing their code into procedures? She can find places where her classmate's program has repeated code, and suggest using a procedure to wrap up that code. The code segment below uses a loop to repeatedly operate on a sequence of numbers.

Which of the following is a benefit of procedures in programming khan academy?

Which of the following is a benefit of procedures for programmers? Programmers can more easily understand programs with procedures, since procedures give names to complex pieces of code.