What Modes Are Used to Read and Write a Binary File?
Welcome
Hi! If yous desire to larn how to work with files in Python, and so this commodity is for you. Working with files is an of import skill that every Python programmer should acquire, so let's get started.
In this article, you will acquire:
- 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 exist raised when you work with files.
- and more!
Let'due south begin! ✨
🔹 Working with Files: Basic Syntax
I of the most important functions that you volition need to use as you work with files in Python is open() , a congenital-in function that opens a file and allows your plan to use information technology and piece of work with it.
This is the bones syntax:
💡 Tip: These are the ii most commonly used arguments to call this part. At that place are 6 additional optional arguments. To learn more well-nigh them, please read this commodity in the documentation.
Beginning Parameter: File
The first parameter of the open up() function is file , the accented 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 open() part.
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 every bit the Python script, like this:
But if the file is within a nested folder, like this:
Then we need to utilize a specific path to tell the function that the file is within another folder.
In this case, this would exist the path:
open("data/names.txt") Detect that we are writing data/ showtime (the name of the binder followed by a /) and then names.txt (the name of the file with the extension).
💡 Tip: The three letters .txt that follow the dot in names.txt is the "extension" of the file, or its type. In this instance, .txt indicates that information technology'due south a text file.
Second Parameter: Mode
The 2nd parameter of the open up() role is the mode , a string with one character. That single grapheme basically tells Python what you are planning to do with the file in your program.
Modes available are:
- Read (
"r"). - Append (
"a") - Write (
"due west") - Create (
"x")
Y'all tin can too choose to open up the file in:
- Text style (
"t") - Binary manner (
"b")
To use text or binary manner, you would demand to add these characters to the main mode. For case: "wb" means writing in binary mode.
💡 Tip: The default modes are read ("r") and text ("t"), which means "open up for reading text" ("rt"), so you don't need to specify them in open up() if you want to employ them because they are assigned by default. You can simply write open up(<file>).
Why Modes?
It actually makes sense for Python to grant only certain permissions based what y'all are planning to exercise with the file, correct? Why should Python allow your program to do more than necessary? This is basically why modes exist.
Call back most it — allowing a plan to do more than necessary tin can problematic. For example, if yous only need to read the content of a file, it tin can be unsafe to permit your program to change it unexpectedly, which could potentially introduce bugs.
🔸 How to Read a File
Now that yous know more virtually the arguments that the open() role takes, let'southward meet how you can open up a file and store information technology in a variable to use information technology in your program.
This is the bones syntax:
We are merely assigning the value returned to a variable. For example:
names_file = open("data/names.txt", "r") I know you might exist asking: what blazon of value is returned past open() ?
Well, a file object.
Let's talk a little flake nearly them.
File Objects
Co-ordinate to the Python Documentation, a file object is:
An object exposing a file-oriented API (with methods such equally read() or write()) to an underlying resource.
This is basically telling us that a file object is an object that lets us piece of work and interact with existing files in our Python program.
File objects have attributes, such every bit:
- proper name: the proper noun of the file.
- closed:
Trueif the file is airtight.Imitationotherwise. - mode: the way used to open the file.
For example:
f = open("data/names.txt", "a") impress(f.fashion) # Output: "a" Now permit's see how yous tin can access the content of a file through a file object.
Methods to Read a File
For u.s.a. to be able to work file objects, nosotros need to have a fashion to "interact" with them in our program and that is exactly what methods do. Permit'due south encounter some of them.
Read()
The starting time method that yous demand to larn near is read() , which returns the unabridged content of the file as a string.
Here nosotros take an case:
f = open("data/names.txt") print(f.read()) The output is:
Nora Gino Timmy William You tin utilize the type() function to confirm that the value returned by f.read() is a string:
print(type(f.read())) # Output <course 'str'> Yes, information technology's a cord!
In this instance, the unabridged file was printed considering we did non specify a maximum number of bytes, but nosotros can exercise this besides.
Here we have an example:
f = open("data/names.txt") print(f.read(iii)) 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 practise this, you need to call the close() method, like this:
Readline() vs. Readlines()
You tin can read a file line by line with these two methods. They are slightly different, so let's see them in particular.
readline() reads one line of the file until it reaches the end of that line. A trailing newline character (\due north) is kept in the string.
💡 Tip: Optionally, you can laissez passer the size, the maximum number of characters that you desire to include in the resulting string.
For example:
f = open up("data/names.txt") impress(f.readline()) f.shut() The output is:
Nora This is the first line of the file.
In contrast, readlines() returns a list with all the lines of the file as individual elements (strings). This is the syntax:
For instance:
f = open("data/names.txt") impress(f.readlines()) f.close() The output is:
['Nora\n', 'Gino\n', 'Timmy\due north', 'William'] Notice that there is a \n (newline grapheme) at the cease of each string, except the last one.
💡 Tip: You can become the same list with list(f).
You tin work with this listing in your programme by assigning it to a variable or using it in a loop:
f = open("data/names.txt") for line in f.readlines(): # Practice 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: # Practise something with each line f.shut() Those are the main methods used to read file objects. Now let's see how y'all can create files.
🔹 How to Create a File
If you need to create a file "dynamically" using Python, y'all can practise it with the "x" manner.
Let's come across how. This is the basic syntax:
Here's an instance. This is my current working directory:
If I run this line of lawmaking:
f = open("new_file.txt", "x") A new file with that proper noun is created:
With this mode, y'all tin can create a file and then write to information technology dynamically using methods that you will learn in only a few moments.
💡 Tip: The file will be initially empty until you alter it.
A curious thing is that if you attempt to run this line again and a file with that proper noun already exists, y'all will see this error:
Traceback (most contempo telephone call last): File "<path>", line 8, in <module> f = open("new_file.txt", "ten") FileExistsError: [Errno 17] File exists: 'new_file.txt' According to the Python Documentation, this exception (runtime fault) is:
Raised when trying to create a file or directory which already exists.
Now that yous know how to create a file, let's see how you can alter it.
🔸 How to Modify a File
To modify (write to) a file, you need to use the write() method. Y'all accept ii ways to do it (append or write) based on the way that y'all choose to open it with. Let'due south see them in item.
Append
"Appending" ways calculation something to the cease of some other affair. The "a" fashion allows you to open up a file to append some content to it.
For example, if we accept this file:
And we want to add together a new line to it, nosotros tin can open information technology using the "a" mode (append) and then, 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'south an example:
f = open("data/names.txt", "a") f.write("\nNew Line") f.close() 💡 Tip: Detect that I'thou adding \due north before the line to betoken that I desire the new line to appear equally a divide line, not every bit 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 f.shut() runs.
Write
Sometimes, you may desire to delete the content of a file and replace it entirely with new content. You tin do this with the write() method if you lot open the file with the "w" mode.
Here we accept this text file:
If I run this script:
f = open up("data/names.txt", "w") f.write("New Content") f.shut() This is the result:
As yous can run into, opening a file with the "w" style and then writing to it replaces the existing content.
💡 Tip: The write() method returns the number of characters written.
If you desire to write several lines at one time, you can utilize the writelines() 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:
f = open("information/names.txt", "a") f.writelines(["\nline1", "\nline2", "\nline3"]) f.close() The lines are added to the end of the file:
Open File For Multiple Operations
Now you lot know how to create, read, and write to a file, but what if you lot want to exercise more than one thing in the aforementioned program? Let'due south run across what happens if we effort to practise this with the modes that you have learned and so far:
If yous open a file in "r" mode (read), and so try to write to it:
f = open("information/names.txt") f.write("New Content") # Trying to write f.close() You will get this error:
Traceback (most recent call last): File "<path>", line nine, in <module> f.write("New Content") io.UnsupportedOperation: non writable Similarly, if yous open a file in "westward" style (write), and so try to read information technology:
f = open up("information/names.txt", "w") impress(f.readlines()) # Trying to read f.write("New Content") f.shut() You will see this error:
Traceback (virtually recent call terminal): File "<path>", line 14, in <module> print(f.readlines()) io.UnsupportedOperation: not readable The same will occur with the "a" (suspend) manner.
How can we solve this? To exist able to read a file and perform another performance in the same program, you need to add the "+" symbol to the mode, similar this:
f = open("data/names.txt", "w+") # Read + Write f = open up("data/names.txt", "a+") # Read + Append f = open("information/names.txt", "r+") # Read + Write Very useful, right? This is probably what you will apply in your programs, merely be sure to include only the modes that y'all demand to avert potential bugs.
Sometimes files are no longer needed. Let's see how you tin can delete files using Python.
🔹 How to Delete Files
To remove a file using Python, you demand to import a module called os which contains functions that collaborate with your operating arrangement.
💡 Tip: A module is a Python file with related variables, functions, and classes.
Peculiarly, you need the remove() function. This function takes the path to the file as argument and deletes the file automatically.
Allow'south see an example. We want to remove the file called sample_file.txt.
To do information technology, we write this code:
import os os.remove("sample_file.txt") - The first line:
import boneis called an "import statement". This statement is written at the top of your file and it gives you admission to the functions defined in theosmodule. - The 2d line:
os.remove("sample_file.txt")removes the file specified.
💡 Tip: you can employ an absolute or a relative path.
Now that you lot know how to delete files, allow'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 demand to remember to shut a file at the end of your programme and you have access to the file in the item part of the plan that you choose.
Syntax
This is an instance of a context manager used to piece of work with files:
💡 Tip: The body of the context director has to be indented, merely like we indent loops, functions, and classes. If the lawmaking is non indented, it volition non be considered part of the context manager.
When the torso of the context director has been completed, the file closes automatically.
with open("<path>", "<fashion>") as <var>: # Working with the file... # The file is closed here! Example
Here'south an example:
with open("data/names.txt", "r+") equally f: print(f.readlines()) This context manager 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 can't be read without opening it over again. But wait! We have a line that tries to read information technology once again, right here beneath:
with open up("data/names.txt", "r+") as f: impress(f.readlines()) print(f.readlines()) # Trying to read the file again, outside of the context managing director Let's see what happens:
Traceback (most recent call concluding): File "<path>", line 21, in <module> print(f.readlines()) ValueError: I/O operation on closed file. This error is thrown because nosotros are trying to read a closed file. Awesome, correct? The context manager does all the heavy work for united states, it is readable, and curtailed.
🔹 How to Handle Exceptions When Working With Files
When you're working with files, errors tin occur. Sometimes y'all may not accept the necessary permissions to modify or access a file, or a file might non even exist.
Every bit a programmer, you demand to foresee these circumstances and handle them in your program to avert sudden crashes that could definitely impact the user experience.
Let's see some of the most common exceptions (runtime errors) that you might find when y'all piece of work with files:
FileNotFoundError
According 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 y'all're trying to open doesn't exist in your current working directory:
f = open("names.txt") You will see this error:
Traceback (about contempo call last): File "<path>", line eight, in <module> f = open("names.txt") FileNotFoundError: [Errno 2] No such file or directory: 'names.txt' Allow's interruption this error downwards this line by line:
-
File "<path>", line 8, in <module>. This line tells you that the error was raised when the lawmaking 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 2] No such file or directory: 'names.txt'. This line says that aFileNotFoundErrorexception was raised considering the file or directorynames.txtdoesn't be.
💡 Tip: Python is very descriptive with the mistake letters, correct? This is a huge advantage during the procedure of debugging.
PermissionError
This 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 case filesystem permissions.
This exception is raised when you are trying to read or modify a file that don't take permission to admission. If you try to practise then, you volition see this error:
Traceback (about recent telephone call terminal): File "<path>", line 8, in <module> f = open("<file_path>") PermissionError: [Errno xiii] Permission denied: 'data' IsADirectoryError
According to the Python Documentation, this exception is:
Raised when a file operation is requested on a directory.
This particular exception is raised when y'all endeavour to open or work on a directory instead of a file, so be actually conscientious with the path that you lot pass equally statement.
How to Handle Exceptions
To handle these exceptions, you can use a endeavour/except statement. With this argument, y'all can "tell" your program what to do in example something unexpected happens.
This is the basic syntax:
endeavor: # Try to run this code except <type_of_exception>: # If an exception of this type is raised, finish the process and jump to this block Hither you can see an example with FileNotFoundError:
try: f = open("names.txt") except FileNotFoundError: print("The file doesn't exist") This basically says:
- Try to open the file
names.txt. - If a
FileNotFoundErroris thrown, don't crash! Simply print a descriptive statement for the user.
💡 Tip: You tin can choose how to handle the situation by writing the appropriate lawmaking in the except cake. Possibly yous could create a new file if it doesn't exist already.
To close the file automatically later on the task (regardless of whether an exception was raised or not in the endeavour block) you tin add the finally block.
endeavor: # Try to run this code except <exception>: # If this exception is raised, stop the procedure immediately and jump to this block finally: # Do this after running the code, fifty-fifty if an exception was raised This is an example:
endeavor: f = open up("names.txt") except FileNotFoundError: print("The file doesn't exist") finally: f.close() There are many ways to customize the attempt/except/finally statement and you tin even add an else cake to run a block of code merely if no exceptions were raised in the endeavor block.
💡 Tip: To learn more well-nigh exception handling in Python, you may like to read my commodity: "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 ain set of methods that you tin can use to work with them in your programme.
- Context Managers help y'all 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
FileNotFoundError,PermissionErrorandIsADirectoryError. They can be handled using try/except/else/finally.
I really hope you liked my article and establish it helpful. At present you can work with files in your Python projects. Check out my online courses. Follow me on Twitter. ⭐️
Learn to lawmaking for complimentary. freeCodeCamp's open up source curriculum has helped more twoscore,000 people get 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 "What Modes Are Used to Read and Write a Binary File?"
Post a Comment