Your Program Should Prompt for the Filename to Read
Welcome
Hi! If y'all want to larn how to work with files in Python, then this article is for y'all. Working with files is an of import skill that every Python developer should acquire, and so let's get started.
In this article, you will learn:
- How to open up 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 piece of work with files.
- and more!
Let'south begin! ✨
🔹 Working with Files: Basic Syntax
One of the most of import functions that you will demand to use equally you work with files in Python is open up()
, 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 role. There are vi boosted optional arguments. To learn more almost them, please read this article in the documentation.
First Parameter: File
The first parameter of the open()
part is file
, the accented or relative path to the file that yous 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 up()
function.
For example, the path in this function 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 aforementioned directory or folder equally the Python script, similar this:
Just if the file is inside a nested binder, like this:
And so nosotros demand to employ a specific path to tell the function that the file is within some other folder.
In this instance, this would be the path:
open up("data/names.txt")
Notice that we are writing data/
first (the proper noun of the folder followed past a /
) so names.txt
(the 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 case, .txt
indicates that it's a text file.
Second Parameter: Mode
The second parameter of the open()
part is the mode
, a string with i character. That unmarried character basically tells Python what yous are planning to do with the file in your plan.
Modes available are:
- Read (
"r"
). - Append (
"a"
) - Write (
"w"
) - Create (
"x"
)
You tin as well choose to open the file in:
- Text way (
"t"
) - Binary mode (
"b"
)
To use text or binary mode, you lot would need to add these characters to the master way. For example: "wb"
ways writing in binary mode.
💡 Tip: The default modes are read ("r"
) and text ("t"
), which means "open for reading text" ("rt"
), so y'all don't demand to specify them in open()
if you want to use them because they are assigned past default. You can merely write open up(<file>)
.
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 exercise more than necessary? This is basically why modes exist.
Remember about it — allowing a programme to do more than than necessary can problematic. For case, if you just demand to read the content of a file, information technology can exist dangerous to permit your plan to modify information technology unexpectedly, which could potentially innovate bugs.
🔸 How to Read a File
At present that you know more almost the arguments that the open up()
function takes, permit'southward see how y'all can open up a file and store it in a variable to use it in your program.
This is the basic syntax:
We are but assigning the value returned to a variable. For example:
names_file = open("data/names.txt", "r")
I know you might exist asking: what type of value is returned by open()
?
Well, a file object.
Let's talk a little chip about them.
File Objects
Co-ordinate 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 us that a file object is an object that lets united states of america work and interact with existing files in our Python program.
File objects have attributes, such as:
- name: the name of the file.
- airtight:
True
if the file is closed.False
otherwise. - fashion: the mode used to open the file.
For instance:
f = open("data/names.txt", "a") print(f.style) # Output: "a"
Now let's see how yous can access the content of a file through a file object.
Methods to Read a File
For us to be able to piece of work file objects, we need to have a way to "collaborate" with them in our plan and that is exactly what methods do. Permit's see some of them.
Read()
The first method that you need to acquire about is read()
, which returns the entire content of the file as a string.
Hither we have an example:
f = open("data/names.txt") print(f.read())
The output is:
Nora Gino Timmy William
Y'all can 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 string!
In this case, the unabridged file was printed because we did not specify a maximum number of bytes, but nosotros can practice this as well.
Hither nosotros have an instance:
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 chore has been completed to gratuitous the resources associated to the file. To practise this, you need to call the shut()
method, like this:
Readline() vs. Readlines()
Y'all tin can read a file line by line with these ii methods. They are slightly unlike, so permit'due south see them in detail.
readline()
reads one line of the file until information technology reaches the end of that line. A abaft newline character (\n
) 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 instance:
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 equally individual elements (strings). This is the syntax:
For example:
f = open up("data/names.txt") impress(f.readlines()) f.close()
The output is:
['Nora\n', 'Gino\n', 'Timmy\northward', 'William']
Observe that there is a \due north
(newline character) at the end of each cord, except the last one.
💡 Tip: You can get the same list with listing(f)
.
You can piece of work with this listing in your plan by assigning it to a variable or using it in a loop:
f = open("data/names.txt") for line in f.readlines(): # Do something with each line f.close()
Nosotros tin can as well iterate over f
directly (the file object) in a loop:
f = open up("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'southward come across how y'all can create files.
🔹 How to Create a File
If you need to create a file "dynamically" using Python, you can exercise it with the "x"
fashion.
Let'southward see 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 can create a file and then write to it dynamically using methods that you will acquire in just a few moments.
💡 Tip: The file will exist initially empty until you alter it.
A curious matter is that if you try to run this line again and a file with that name already exists, you will see this error:
Traceback (almost recent 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 mistake) 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 tin can modify information technology.
🔸 How to Modify a File
To change (write to) a file, you need to employ the write()
method. Yous have two means to practice 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 cease of another affair. The "a"
manner allows you to open a file to append some content to information technology.
For example, if nosotros have this file:
And we want to add a new line to it, we can open up it using the "a"
mode (append) and and then, telephone call the write()
method, passing the content that nosotros want to suspend as statement.
This is the basic syntax to telephone call the write()
method:
Hither's an example:
f = open("data/names.txt", "a") f.write("\nNew Line") f.close()
💡 Tip: Detect 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 at present, after running the script:
💡 Tip: The new line might not be displayed in the file until f.shut()
runs.
Write
Sometimes, you may want to delete the content of a file and supercede information technology entirely with new content. Y'all can do this with the write()
method if you open the file with the "w"
way.
Here we take this text file:
If I run this script:
f = open("information/names.txt", "w") f.write("New Content") f.close()
This is the effect:
As y'all can see, opening a file with the "west"
mode and then writing to it replaces the existing content.
💡 Tip: The write()
method returns the number of characters written.
If you want to write several lines at once, you can use the writelines()
method, which takes a listing 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("data/names.txt", "a") f.writelines(["\nline1", "\nline2", "\nline3"]) f.close()
The lines are added to the finish of the file:
Open File For Multiple Operations
Now y'all know how to create, read, and write to a file, merely what if you lot want to do more than 1 affair in the same programme? Let's come across what happens if nosotros try to do this with the modes that you have learned so far:
If you open a file in "r"
way (read), and and so try to write to it:
f = open("data/names.txt") f.write("New Content") # Trying to write f.shut()
You lot volition get this fault:
Traceback (nearly contempo phone call final): File "<path>", line ix, 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", "due west") print(f.readlines()) # Trying to read f.write("New Content") f.close()
You volition see this error:
Traceback (near recent call last): File "<path>", line 14, in <module> impress(f.readlines()) io.UnsupportedOperation: not readable
The same will occur with the "a"
(append) mode.
How can we solve this? To exist able to read a file and perform another performance in the same programme, you demand to add together the "+"
symbol to the mode, similar this:
f = open("data/names.txt", "west+") # Read + Write
f = open up("data/names.txt", "a+") # Read + Append
f = open("data/names.txt", "r+") # Read + Write
Very useful, right? This is probably what yous will use in your programs, but exist sure to include merely 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 os
which contains functions that interact with your operating organization.
💡 Tip: A module is a Python file with related variables, functions, and classes.
Specially, you need the remove()
function. This function takes the path to the file as argument and deletes the file automatically.
Let's see an case. Nosotros want to remove the file called sample_file.txt
.
To do it, we write this code:
import bone bone.remove("sample_file.txt")
- The first line:
import bone
is called an "import argument". This argument is written at the top of your file and it gives you lot access to the functions divers in theos
module. - The 2nd line:
os.remove("sample_file.txt")
removes the file specified.
💡 Tip: yous can use an absolute or a relative path.
Now that you know how to delete files, let'south see an interesting tool... Context Managers!
🔸 Run across Context Managers
Context Managers are Python constructs that will make your life much easier. Past using them, you don't demand to remember to close a file at the stop of your program and yous have access to the file in the particular part of the program that you choose.
Syntax
This is an example of a context director used to work with files:
💡 Tip: The trunk of the context managing director has to be indented, just like we indent loops, functions, and classes. If the code is non indented, information technology will non be considered part of the context managing director.
When the trunk of the context manager has been completed, the file closes automatically.
with open("<path>", "<fashion>") as <var>: # Working with the file... # The file is airtight hither!
Instance
Here's 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 body of the context manager to refer to the file object.
Trying to Read information technology Again
After the body has been completed, the file is automatically closed, so it can't be read without opening it again. But expect! Nosotros have a line that tries to read it again, right here below:
with open up("data/names.txt", "r+") every bit f: print(f.readlines()) print(f.readlines()) # Trying to read the file again, outside of the context manager
Permit's meet what happens:
Traceback (about recent call last): File "<path>", line 21, in <module> print(f.readlines()) ValueError: I/O operation on closed file.
This error is thrown because we are trying to read a closed file. Awesome, right? The context manager does all the heavy piece of work for us, it is readable, and concise.
🔹 How to Handle Exceptions When Working With Files
When y'all're working with files, errors can occur. Sometimes you may non have the necessary permissions to modify or access a file, or a file might not fifty-fifty be.
As a developer, you lot 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 might find when yous work with files:
FileNotFoundError
According to the Python Documentation, this exception is:
Raised when a file or directory is requested but doesn't be.
For example, if the file that you lot're trying to open up doesn't exist in your current working directory:
f = open("names.txt")
You will see this error:
Traceback (most contempo call last): File "<path>", line 8, in <module> f = open("names.txt") FileNotFoundError: [Errno 2] No such file or directory: 'names.txt'
Let's intermission this mistake down this line past 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 8
was executed in<module>
. -
f = open("names.txt")
. This is the line that acquired the error. -
FileNotFoundError: [Errno 2] No such file or directory: 'names.txt'
. This line says that aFileNotFoundError
exception was raised because the file or directorynames.txt
doesn't exist.
💡 Tip: Python is very descriptive with the error messages, correct? This is a huge reward during the process 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 adequate access rights - for instance filesystem permissions.
This exception is raised when yous are trying to read or alter a file that don't have permission to admission. If you try to do and so, you will run into this error:
Traceback (most contempo phone call terminal): File "<path>", line 8, in <module> f = open("<file_path>") PermissionError: [Errno 13] Permission denied: 'data'
IsADirectoryError
Co-ordinate to the Python Documentation, this exception is:
Raised when a file functioning 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 plan what to exercise in case something unexpected happens.
This is the basic syntax:
try: # Try to run this code except <type_of_exception>: # If an exception of this blazon is raised, stop the process and leap to this cake
Hither you can see an example with FileNotFoundError
:
try: f = open("names.txt") except FileNotFoundError: print("The file doesn't be")
This basically says:
- Endeavour to open the file
names.txt
. - If a
FileNotFoundError
is thrown, don't crash! Simply impress a descriptive statement for the user.
💡 Tip: You can choose how to handle the state of affairs by writing the appropriate code in the except
block. Perhaps you could create a new file if it doesn't be already.
To shut the file automatically after the task (regardless of whether an exception was raised or not in the try
cake) you tin add the finally
block.
attempt: # Try to run this lawmaking except <exception>: # If this exception is raised, cease the process immediately and bound to this block finally: # Do this after running the code, even if an exception was raised
This is an example:
attempt: f = open("names.txt") except FileNotFoundError: print("The file doesn't exist") finally: f.close()
There are many ways to customize the try/except/finally statement and y'all can even add an else
block to run a block of code only if no exceptions were raised in the try
cake.
💡 Tip: To acquire more about exception handling in Python, you lot may like to read my commodity: "How to Handle Exceptions in Python: A Detailed Visual Introduction".
🔸 In Summary
- You tin can create, read, write, and delete files using Python.
- File objects have their own set of methods that you tin apply to piece of work with them in your program.
- Context Managers help you work with files and manage them past closing them automatically when a job has been completed.
- Exception treatment is fundamental in Python. Common exceptions when yous are working with files include
FileNotFoundError
,PermissionError
andIsADirectoryError
. They can be handled using try/except/else/finally.
I really hope you liked my article and found information technology helpful. At present y'all can work with files in your Python projects. 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 get jobs equally 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 "Your Program Should Prompt for the Filename to Read"
Post a Comment