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. Show
In this article, you will learn:
Let's begin! ✨ 🔹 Working with Files: Basic SyntaxOne of the most important functions that you will need to use as you work with files in Python is 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: 💡 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: FileThe first parameter of the 0 function is 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 0 function.For example, the path in this function call:
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: But if the file is within a nested folder, like this: The names.txt file is in the "data" folderThen 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:
Notice that we are writing 3 first (the name of the folder followed by a 4) and then 5 (the name of the file with the extension).💡 Tip: The three letters 6 that follow the dot in 5 is the "extension" of the file, or its type. In this case, 6 indicates that it's a text file.Second Parameter: ModeThe second parameter of the 0 function is the 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:
You can also choose to open the file in:
To use text or binary mode, you would need to add these characters to the main mode. For example: 7 means writing in binary mode.💡 Tip: The default modes are read ( 1) and text ( 5), which means "open for reading text" ( 0), so you don't need to specify them in 0 if you want to use them because they are assigned by default. You can simply write 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 FileNow that you know more about the arguments that the 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: We are simply assigning the value returned to a variable. For example:
I know you might be asking: what type of value is returned by 9?Well, a file object. Let's talk a little bit about them. File ObjectsAccording 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:
For example:
Now let's see how you can access the content of a file through a file object. Methods to Read a FileFor 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 7, which returns the entire content of the file as a string.Here we have an example:
The output is:
You can use the 8 function to confirm that the value returned by 9 is a string:
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:
The value returned is limited to this number of bytes:
❗️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 0 method, like this: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. 1 reads one line of the file until it reaches the end of that line. A trailing newline character ( 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. For example:
The output is: 0This is the first line of the file. In contrast, 3 returns a list with all the lines of the file as individual elements (strings). This is the syntax:For example: 1The output is: 2Notice that there is a 2 (newline character) at the end of each string, except the last one.💡 Tip: You can get the same list with 5.You can work with this list in your program by assigning it to a variable or using it in a loop: 3We can also iterate over 6 directly (the file object) in a loop: 4Those are the main methods used to read file objects. Now let's see how you can create files. 🔹 How to Create a FileIf you need to create a file "dynamically" using Python, you can do it with the 4 mode.Let's see how. This is the basic syntax: Here's an example. This is my current working directory: If I run this line of code: 5A new file with that name is created: 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: 6According 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 FileTo modify (write to) a file, you need to use the 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 2 mode allows you to open a file to append some content to it.For example, if we have this file: And we want to add a new line to it, we can open it using the 0 mode (append) and then, call the 8 method, passing the content that we want to append as argument.This is the basic syntax to call the 8 method:Here's an example: 7💡 Tip: Notice that I'm adding 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: 💡 Tip: The new line might not be displayed in the file until 4 runs.WriteSometimes, you may want to delete the content of a file and replace it entirely with new content. You can do this with the 8 method if you open the file with the 6 mode.Here we have this text file: If I run this script: 8This is the result: As you can see, opening a file with the 6 mode and then writing to it replaces the existing content.💡 Tip: The 8 method returns the number of characters written.If you want to write several lines at once, you can use the 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: If we run this script: 9The lines are added to the end of the file: Open File For Multiple OperationsNow 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 1 mode (read), and then try to write to it: 0You will get this error: 1Similarly, if you open a file in 3 mode (write), and then try to read it: 2You will see this error: 3The same will occur with the 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 3 symbol to the mode, like this: 4 5 6Very 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 FilesTo remove a file using Python, you need to import a module called 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 5 function. This function takes the path to the file as argument and deletes the file automatically.Let's see an example. We want to remove the file called 6.To do it, we write this code: 7
💡 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 ManagersContext 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. SyntaxThis is an example of a context manager used to work with files: 💡 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. 8ExampleHere's an example: 9This context manager opens the 5 file for read/write operations and assigns that file object to the variable 6. This variable is used in the body of the context manager to refer to the file object.Trying to Read it AgainAfter 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: 0Let's see what happens: 1This 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 FilesWhen 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: FileNotFoundErrorAccording 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: 2You will see this error: 3Let's break this error down this line by line:
💡 Tip: Python is very descriptive with the error messages, right? This is a huge advantage during the process of debugging. PermissionErrorThis 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: 4IsADirectoryErrorAccording 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 ExceptionsTo 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: 5Here you can see an example with 08: 6This basically says:
💡 Tip: You can choose how to handle the situation by writing the appropriate code in the 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 14 block) you can add the 15 block. 7This is an example: 8There are many ways to customize the try/except/finally statement and you can even add an 16 block to run a block of code only if no exceptions were raised in the 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
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 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.
|