Which method is used to display the entire contents of the file?
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: Let's begin! ✨ One of the most important functions that you will need to use as you work with files in Python is 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 this article in the documentation. The first parameter of the 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 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: 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: Notice that we are writing 💡 Tip: The three letters The second parameter of the 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: 💡 Tip: The default modes are read ( 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. Now that you know more about the arguments that the 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 Well, a file object. Let's talk a little bit about them. According to the Python Documentation, a file object is: 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 Here we have an example:
The output is:
You can use the
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 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.
💡 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:
This is the first line of the file. In contrast, For example:
The output is:
Notice that there is a 💡 Tip: You can get the same list with You can work with this list in your program by assigning it to a variable or using it in a loop:
We can also iterate over
Those 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 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:
A 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:
According to the Python Documentation, 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 Append"Appending" means adding something to the end of another thing. The For example, if we have this file: And we want to add a new line to it, we
can open it using the This is the basic syntax to call the Here's an example:
💡 Tip: Notice that I'm adding This is the file now, after running the script: 💡 Tip: The new line might not be displayed in the file until WriteSometimes, you may want to delete the content of a
file and replace it entirely with new content. You can do this with the Here we have this text file: If I run this script:
This is the result: As you can see, opening a file with the 💡 Tip: The If you want to write several lines at once, you can use the Here's an example. This is the initial file: If we run this script:
The 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
You will get this error:
Similarly, if you open a file in
You will see this error:
The same will occur with the 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
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 FilesTo remove a file using Python, you need to import a module called 💡 Tip: A module is a Python file with related variables, functions, and classes. Particularly, you need the Let's see an example. We want to remove the file called To do it, we write this code:
💡 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.
ExampleHere's an example:
This context manager opens the 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:
Let's see what happens:
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 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 Python Documentation, 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:
You will see this error:
Let'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 Python Documentation, 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:
IsADirectoryErrorAccording to the Python Documentation, 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:
Here you can see an example with
This basically says:
💡 Tip: You can choose how to handle the situation by writing the appropriate code in the To close the file automatically after the task (regardless of whether an exception was raised or not in the
This is an example:
There are many ways to customize the try/except/finally statement and you can even add an 💡 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. ⭐️ Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started Which command is used to display the contents of a file?You can also use the cat command to display the contents of one or more files on your screen. Combining the cat command with the pg command allows you to read the contents of a file one full screen at a time. You can also display the contents of files by using input and output redirection.
Which function is used to read entire file in the form of a list?fgets()– This function is used to read strings from files. fscanf()– This function is used to read formatted input from a file.
How can we see the contents of a file?You can also display the contents of files by using input and output redirection.. Using the pg command. Use the pg command to read the files named in the File parameter and writes them to standard output one screen at a time.. Using the more or page commands. ... . cat command.. Which file method will read the file contents all at once?The read() method is going to read all of the content of the file as one string. This is a good method to use if you don't have a lot of content in the text file. This method can take in an optional parameter called size.
|