Check if Line Being Read by File Equals a Variable
Welcome
Hi! If you want to larn how to work with files in Python, then this article is for yous. Working with files is an of import skill that every Python developer should learn, and so permit'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 alter a file.
- How to close a file.
- How to open files for multiple operations.
- How to piece of 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 exist raised when you piece of work with files.
- and more!
Let'due south begin! ✨
🔹 Working with Files: Bones Syntax
One of the about important functions that you will need to utilise equally yous work with files in Python is open up() , a built-in part that opens a file and allows your program to use it and work with information technology.
This is the basic syntax:
💡 Tip: These are the two most commonly used arguments to call this function. There are vi additional optional arguments. To learn more about them, please read this article in the documentation.
Starting time Parameter: File
The first parameter of the open() function is file , the absolute or relative path to the file that you are trying to work with.
Nosotros normally apply a relative path, which indicates where the file is located relative to the location of the script (Python file) that is calling the open() role.
For example, the path in this function phone call:
open up("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:
But if the file is within a nested folder, like this:
Then we need to utilise a specific path to tell the function that the file is within some other folder.
In this case, this would be the path:
open("data/names.txt") Notice that we are writing information/ first (the proper noun of the binder followed by a /) then names.txt (the proper name of the file with the extension).
💡 Tip: The 3 letters .txt that follow the dot in names.txt is the "extension" of the file, or its type. In this example, .txt indicates that it's a text file.
Second Parameter: Mode
The second parameter of the open() function is the style , a cord with one grapheme. That single character basically tells Python what you are planning to do with the file in your programme.
Modes available are:
- Read (
"r"). - Append (
"a") - Write (
"w") - Create (
"x")
You lot can too cull to open the file in:
- Text manner (
"t") - Binary mode (
"b")
To use text or binary mode, yous would demand to add together these characters to the principal mode. For instance: "wb" means writing in binary style.
💡 Tip: The default modes are read ("r") and text ("t"), which means "open for reading text" ("rt"), then you don't demand to specify them in open() if you want to apply them considering they are assigned by default. You tin can but write open(<file>).
Why Modes?
It really makes sense for Python to grant merely certain permissions based what you are planning to do with the file, right? Why should Python allow your programme to do more than than necessary? This is basically why modes exist.
Retrieve nigh it — assuasive a plan to do more than than necessary can problematic. For example, if you only demand to read the content of a file, information technology can be dangerous to permit your programme to modify information technology unexpectedly, which could potentially introduce bugs.
🔸 How to Read a File
Now that you lot know more than about the arguments that the open() part takes, let's meet how yous can open a file and store information technology in a variable to utilize it in your program.
This is the basic syntax:
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 blazon of value is returned by open() ?
Well, a file object.
Allow's talk a piddling flake about them.
File Objects
According to the Python Documentation, 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 the states that a file object is an object that lets us piece of work and interact with existing files in our Python programme.
File objects have attributes, such as:
- proper noun: the proper noun of the file.
- closed:
Trueif the file is closed.Falseotherwise. - mode: the mode used to open up the file.
For case:
f = open up("data/names.txt", "a") print(f.mode) # Output: "a" Now let's see how you lot can access the content of a file through a file object.
Methods to Read a File
For united states of america to be able to work file objects, we need to accept a way to "interact" with them in our program and that is exactly what methods practice. Let's run into some of them.
Read()
The beginning method that y'all demand to learn most is read() , which returns the entire content of the file as a string.
Here nosotros have an example:
f = open("data/names.txt") print(f.read()) The output is:
Nora Gino Timmy William You tin use the type() role to confirm that the value returned by f.read() is a cord:
print(type(f.read())) # Output <course 'str'> Aye, information technology's a cord!
In this case, the entire file was printed considering we did not specify a maximum number of bytes, but we tin do this every bit well.
Here we have an example:
f = open up("data/names.txt") impress(f.read(3)) The value returned is limited to this number of bytes:
Nor ❗️Important: Yous need to shut a file afterwards the task has been completed to free the resources associated to the file. To do this, you need to call the shut() method, similar this:
Readline() vs. Readlines()
Y'all tin read a file line by line with these ii methods. They are slightly unlike, so permit's encounter them in detail.
readline() reads 1 line of the file until it reaches the end of that line. A trailing newline character (\n) is kept in the string.
💡 Tip: Optionally, y'all tin pass the size, the maximum number of characters that yous want to include in the resulting string.
For example:
f = open up("data/names.txt") print(f.readline()) f.close() The output is:
Nora This is the first line of the file.
In contrast, readlines() returns a listing with all the lines of the file as individual elements (strings). This is the syntax:
For example:
f = open up("data/names.txt") print(f.readlines()) f.shut() The output is:
['Nora\n', 'Gino\n', 'Timmy\n', 'William'] Find that there is a \due north (newline character) at the finish of each string, except the last ane.
💡 Tip: Yous tin can become the same list with list(f).
Yous tin work with this list in your program by assigning it to a variable or using it in a loop:
f = open up("data/names.txt") for line in f.readlines(): # Practise something with each line f.close() We tin can also iterate over f directly (the file object) in a loop:
f = open("data/names.txt", "r") for line in f: # Do something with each line f.close() 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, y'all can do it with the "x" manner.
Allow's run across how. This is the bones syntax:
Here's an example. This is my current working directory:
If I run this line of code:
f = open("new_file.txt", "x") A new file with that proper noun is created:
With this mode, you lot can create a file then write to information technology dynamically using methods that yous will learn in just a few moments.
💡 Tip: The file will be initially empty until y'all change information technology.
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:
Traceback (nearly contempo telephone call final): File "<path>", line 8, in <module> f = open("new_file.txt", "10") FileExistsError: [Errno 17] File exists: 'new_file.txt' According to the Python Documentation, this exception (runtime error) is:
Raised when trying to create a file or directory which already exists.
At present that y'all know how to create a file, allow'due south see how yous tin can modify it.
🔸 How to Change a File
To modify (write to) a file, you lot demand to utilize the write() method. You take two ways to do it (append or write) based on the way that you choose to open up information technology with. Let's run across them in detail.
Append
"Appending" means adding something to the terminate of another matter. The "a" mode allows you to open a file to suspend some content to it.
For case, if we take this file:
And we want to add a new line to it, we can open information technology using the "a" mode (append) and so, call the write() method, passing the content that we desire to append as argument.
This is the basic syntax to call the write() method:
Here's an example:
f = open("data/names.txt", "a") f.write("\nNew Line") f.close() 💡 Tip: Observe that I'm adding \north before the line to indicate that I want the new line to appear every bit a separate line, not as a continuation of the existing line.
This is the file now, afterwards running the script:
💡 Tip: The new line might non be displayed in the file until f.close() 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 write() method if you open the file with the "w" style.
Hither we have this text file:
If I run this script:
f = open("data/names.txt", "westward") f.write("New Content") f.close() This is the result:
As you can see, opening a file with the "west" mode then writing to information technology replaces the existing content.
💡 Tip: The write() method returns the number of characters written.
If you want to write several lines at once, you tin use the writelines() method, which takes a list of strings. Each string represents a line to be added to the file.
Here'southward an example. This is the initial file:
If we run this script:
f = open("data/names.txt", "a") f.writelines(["\nline1", "\nline2", "\nline3"]) f.shut() The lines are added to the end of the file:
Open File For Multiple Operations
At present you know how to create, read, and write to a file, but what if you want to practice more than one thing in the aforementioned plan? Permit'southward see what happens if nosotros try to do this with the modes that y'all have learned then far:
If you lot open up a file in "r" mode (read), then try to write to it:
f = open up("information/names.txt") f.write("New Content") # Trying to write f.close() You will go this error:
Traceback (well-nigh recent call terminal): File "<path>", line 9, in <module> f.write("New Content") io.UnsupportedOperation: not writable Similarly, if you open up a file in "w" mode (write), and then try to read it:
f = open("data/names.txt", "westward") print(f.readlines()) # Trying to read f.write("New Content") f.close() You will see this error:
Traceback (well-nigh contempo call last): File "<path>", line xiv, in <module> print(f.readlines()) io.UnsupportedOperation: not readable The same will occur with the "a" (append) style.
How can we solve this? To be able to read a file and perform another operation in the same programme, you demand to add the "+" symbol to the mode, similar this:
f = open("data/names.txt", "w+") # Read + Write f = open("information/names.txt", "a+") # Read + Suspend f = open("information/names.txt", "r+") # Read + Write Very useful, right? This is probably what you will use in your programs, only be certain to include only the modes that you need to avert potential bugs.
Sometimes files are no longer needed. Let'due south 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 os 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 remove() function. This function takes the path to the file equally argument and deletes the file automatically.
Let'south see an example. Nosotros want to remove the file called sample_file.txt.
To do information technology, nosotros write this code:
import bone bone.remove("sample_file.txt") - The starting time line:
import osis called an "import statement". This statement is written at the top of your file and it gives yous access to the functions defined in thebonemodule. - The second line:
os.remove("sample_file.txt")removes the file specified.
💡 Tip: you lot can use an absolute or a relative path.
Now that y'all know how to delete files, let'southward meet an interesting tool... Context Managers!
🔸 See Context Managers
Context Managers are Python constructs that volition make your life much easier. By using them, you don't need to remember to close a file at the end of your programme and yous have admission to the file in the particular part of the plan that you choose.
Syntax
This is an example of a context manager used to work with files:
💡 Tip: The torso of the context manager has to be indented, just similar we indent loops, functions, and classes. If the lawmaking is not indented, it will not be considered office of the context manager.
When the torso of the context manager has been completed, the file closes automatically.
with open up("<path>", "<fashion>") as <var>: # Working with the file... # The file is closed here! Example
Here's an example:
with open("data/names.txt", "r+") as f: print(f.readlines()) This context director opens the names.txt file for read/write operations and assigns that file object to the variable f. This variable is used in the torso 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 airtight, and then it tin can't be read without opening it again. Simply look! We have a line that tries to read information technology once more, right here below:
with open up("data/names.txt", "r+") as f: print(f.readlines()) print(f.readlines()) # Trying to read the file again, outside of the context manager Let'southward see what happens:
Traceback (most recent phone call final): File "<path>", line 21, in <module> impress(f.readlines()) ValueError: I/O operation on airtight file. This error is thrown considering nosotros are trying to read a closed file. Crawly, right? The context director does all the heavy work for us, it is readable, and concise.
🔹 How to Handle Exceptions When Working With Files
When you lot're working with files, errors tin can occur. Sometimes you may not take the necessary permissions to modify or access a file, or a file might not even exist.
As a programmer, y'all need to foresee these circumstances and handle them in your program to avoid sudden crashes that could definitely affect the user feel.
Allow's see some of the most common exceptions (runtime errors) that you lot might detect when yous work with files:
FileNotFoundError
Co-ordinate to the Python Documentation, this exception is:
Raised when a file or directory is requested merely doesn't exist.
For instance, if the file that you're trying to open doesn't be in your current working directory:
f = open up("names.txt") Yous will meet this error:
Traceback (well-nigh recent call last): File "<path>", line viii, in <module> f = open("names.txt") FileNotFoundError: [Errno 2] No such file or directory: 'names.txt' Allow's interruption this fault down this line past line:
-
File "<path>", line 8, in <module>. This line tells you that the mistake was raised when the code on the file located in<path>was running. Specifically, whenline 8was executed in<module>. -
f = open("names.txt"). This is the line that caused the error. -
FileNotFoundError: [Errno two] No such file or directory: 'names.txt'. This line says that aFileNotFoundErrorexception was raised because the file or directorynames.txtdoesn't exist.
💡 Tip: Python is very descriptive with the error messages, right? This is a huge reward during the procedure of debugging.
PermissionError
This is another mutual exception when working with files. According to the Python Documentation, this exception is:
Raised when trying to run an operation without the acceptable admission rights - for example filesystem permissions.
This exception is raised when you are trying to read or modify a file that don't take permission to access. If you try to practice so, y'all volition see this mistake:
Traceback (most recent call final): File "<path>", line viii, in <module> f = open("<file_path>") PermissionError: [Errno thirteen] Permission denied: 'data' IsADirectoryError
Co-ordinate to the Python Documentation, this exception is:
Raised when a file operation is requested on a directory.
This particular exception is raised when yous try to open or work on a directory instead of a file, then exist actually careful with the path that you laissez passer as argument.
How to Handle Exceptions
To handle these exceptions, you can apply a try/except statement. With this statement, y'all tin can "tell" your program what to exercise in example something unexpected happens.
This is the bones syntax:
try: # Try to run this code except <type_of_exception>: # If an exception of this type is raised, end the process and jump to this block Here you tin can see an example with FileNotFoundError:
try: f = open up("names.txt") except FileNotFoundError: impress("The file doesn't exist") This basically says:
- Try to open the file
names.txt. - If a
FileNotFoundErroris thrown, don't crash! Simply impress a descriptive statement for the user.
💡 Tip: You lot can cull how to handle the situation by writing the appropriate code in the except block. Mayhap you could create a new file if it doesn't be already.
To close the file automatically after the chore (regardless of whether an exception was raised or not in the endeavour cake) you can add the finally block.
try: # Try to run this code except <exception>: # If this exception is raised, stop the process immediately and bound to this block finally: # Do this later on running the lawmaking, even if an exception was raised This is an example:
try: f = open up("names.txt") except FileNotFoundError: print("The file doesn't exist") finally: f.shut() There are many means to customize the endeavor/except/finally statement and you can even add an else block to run a block of code only if no exceptions were raised in the effort block.
💡 Tip: To learn more about exception handling in Python, yous may like to read my article: "How to Handle Exceptions in Python: A Detailed Visual Introduction".
🔸 In Summary
- Yous can create, read, write, and delete files using Python.
- File objects have their own set up of methods that you can use to work with them in your program.
- Context Managers help you lot 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 y'all are working with files include
FileNotFoundError,PermissionErrorandIsADirectoryError. They can be handled using try/except/else/finally.
I actually hope you liked my article and constitute information technology helpful. Now you tin work with files in your Python projects. Bank check out my online courses. Follow me on Twitter. ⭐️
Learn to code for free. freeCodeCamp'due south open source curriculum has helped more than 40,000 people go jobs as developers. Get started
Source: https://www.freecodecamp.org/news/python-write-to-file-open-read-append-and-other-file-handling-functions-explained/
0 Response to "Check if Line Being Read by File Equals a Variable"
Post a Comment