Read a Customers Status Name and Phone Number From a File Called Potentials.txt
Welcome
Hullo! If you want to learn how to piece of work with files in Python, so this article is for you. Working with files is an important skill that every Python developer should learn, and so let's get started.
In this article, you lot will learn:
- 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 be raised when you lot work with files.
- and more!
Let'southward begin! ✨
🔹 Working with Files: Basic Syntax
One of the most important functions that you volition need to use every bit you piece of work with files in Python is open()
, a built-in function that opens a file and allows your programme to apply information technology and work with it.
This is the basic syntax:
💡 Tip: These are the ii most commonly used arguments to call this office. In that location are vi additional optional arguments. To learn more almost them, delight read this commodity in the documentation.
First Parameter: File
The first parameter of the open()
role is file
, the accented or relative path to the file that you are trying to work with.
We commonly 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()
role.
For example, the path in this function telephone call:
open("names.txt") # The relative path is "names.txt"
Simply contains the proper name of the file. This can exist used when the file that you lot are trying to open up is in the same directory or folder as the Python script, like this:
Simply if the file is within a nested folder, similar this:
And so we demand to utilize a specific path to tell the office that the file is within another folder.
In this example, this would be the path:
open("data/names.txt")
Detect that nosotros are writing data/
first (the proper name of the folder followed past a /
) and 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 case, .txt
indicates that it's a text file.
2nd Parameter: Mode
The 2nd parameter of the open()
part is the fashion
, a cord with one grapheme. That single character basically tells Python what yous are planning to exercise with the file in your program.
Modes bachelor are:
- Read (
"r"
). - Append (
"a"
) - Write (
"due west"
) - Create (
"x"
)
You tin can also cull to open the file in:
- Text mode (
"t"
) - Binary fashion (
"b"
)
To utilise text or binary mode, you would need to add these characters to the chief style. For example: "wb"
means writing in binary way.
💡 Tip: The default modes are read ("r"
) and text ("t"
), which means "open for reading text" ("rt"
), so you don't demand to specify them in open()
if yous want to utilise them because they are assigned past default. You tin only write open up(<file>)
.
Why Modes?
It really makes sense for Python to grant merely certain permissions based what y'all are planning to exercise with the file, right? Why should Python let your program to do more necessary? This is basically why modes exist.
Think about it — allowing a program to practise more than necessary can problematic. For case, if you only need to read the content of a file, it can be dangerous to permit your programme to alter it unexpectedly, which could potentially innovate bugs.
🔸 How to Read a File
Now that you know more about the arguments that the open()
function takes, let'south see how y'all can open a file and store it in a variable to employ it in your plan.
This is the bones syntax:
We are simply assigning the value returned to a variable. For instance:
names_file = open("data/names.txt", "r")
I know yous might be request: what type of value is returned past open()
?
Well, a file object.
Let's talk a little bit 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 united states 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 equally:
- proper name: the proper name of the file.
- airtight:
True
if the file is airtight.False
otherwise. - mode: the mode used to open the file.
For example:
f = open("data/names.txt", "a") print(f.mode) # Output: "a"
Now let's come across how you can access the content of a file through a file object.
Methods to Read a File
For us to be able to work file objects, we demand to have a way to "interact" with them in our program and that is exactly what methods practice. Let's meet some of them.
Read()
The outset method that you need to larn about is read()
, which returns the entire content of the file as a string.
Here we have an example:
f = open up("information/names.txt") print(f.read())
The output is:
Nora Gino Timmy William
Yous can use the blazon()
function to confirm that the value returned by f.read()
is a cord:
print(type(f.read())) # Output <class 'str'>
Yes, it's a string!
In this case, the unabridged file was printed because we did not specify a maximum number of bytes, only we can practise this too.
Here we accept an example:
f = open("information/names.txt") print(f.read(three))
The value returned is limited to this number of bytes:
Nor
❗️Important: You need to close a file subsequently the task has been completed to gratuitous the resources associated to the file. To practice this, you lot need to call the close()
method, like this:
Readline() vs. Readlines()
Y'all tin read a file line by line with these two methods. They are slightly different, so let's meet them in item.
readline()
reads one line of the file until it reaches the end of that line. A trailing newline grapheme (\n
) is kept in the cord.
💡 Tip: Optionally, you can pass the size, the maximum number of characters that you lot want to include in the resulting cord.
For example:
f = open("information/names.txt") print(f.readline()) f.shut()
The output is:
Nora
This is the get-go line of the file.
In contrast, readlines()
returns a list with all the lines of the file as private elements (strings). This is the syntax:
For example:
f = open("information/names.txt") print(f.readlines()) f.close()
The output is:
['Nora\n', 'Gino\north', 'Timmy\due north', 'William']
Notice that there is a \north
(newline character) at the end of each string, except the last one.
💡 Tip: You lot can get the same list with list(f)
.
You can 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 can also iterate over f
straight (the file object) in a loop:
f = open("information/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 permit'southward see how y'all can create files.
🔹 How to Create a File
If y'all demand to create a file "dynamically" using Python, you can do it with the "x"
fashion.
Permit's run into how. This is the basic syntax:
Hither's an case. This is my electric current working directory:
If I run this line of code:
f = open("new_file.txt", "10")
A new file with that proper noun is created:
With this mode, you tin create a file and and then write to it dynamically using methods that yous will acquire in just a few moments.
💡 Tip: The file will be initially empty until you lot alter it.
A curious thing is that if yous endeavour to run this line once again and a file with that proper name already exists, you volition see this error:
Traceback (most recent phone call last): File "<path>", line eight, in <module> f = open("new_file.txt", "x") 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 you know how to create a file, let'south see how you can modify it.
🔸 How to Modify a File
To modify (write to) a file, you need to use the write()
method. You take two ways to do it (suspend or write) based on the mode that you choose to open up it with. Allow'south see them in detail.
Append
"Appending" means adding something to the end of another matter. The "a"
mode allows you to open a file to suspend some content to it.
For example, 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) then, phone call the write()
method, passing the content that nosotros desire to append equally statement.
This is the basic syntax to call the write()
method:
Here'southward an example:
f = open up("information/names.txt", "a") f.write("\nNew Line") f.close()
💡 Tip: Observe that I'thousand adding \n
before the line to betoken that I desire the new line to appear as a split up line, not as a continuation of the existing line.
This is the file at present, afterwards running the script:
💡 Tip: The new line might non exist displayed in the file until f.close()
runs.
Write
Sometimes, y'all may want to delete the content of a file and replace it entirely with new content. Y'all can do this with the write()
method if yous open the file with the "due west"
mode.
Here we have this text file:
If I run this script:
f = open up("data/names.txt", "w") f.write("New Content") f.close()
This is the result:
As y'all can meet, opening a file with the "due west"
style so writing to information technology replaces the existing content.
💡 Tip: The write()
method returns the number of characters written.
If you lot want to write several lines at once, you lot 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 instance. This is the initial file:
If we run this script:
f = open up("data/names.txt", "a") f.writelines(["\nline1", "\nline2", "\nline3"]) f.close()
The lines are added to the end of the file:
Open up File For Multiple Operations
Now you know how to create, read, and write to a file, but what if you want to do more than than one thing in the same program? Let's see what happens if we attempt to do this with the modes that you take learned so far:
If you open a file in "r"
mode (read), and then try to write to it:
f = open("data/names.txt") f.write("New Content") # Trying to write f.shut()
You lot will get this error:
Traceback (most recent phone call concluding): File "<path>", line 9, in <module> f.write("New Content") io.UnsupportedOperation: non writable
Similarly, if you open a file in "w"
mode (write), so try to read information technology:
f = open up("data/names.txt", "westward") print(f.readlines()) # Trying to read f.write("New Content") f.close()
You will see this error:
Traceback (most recent telephone call last): File "<path>", line fourteen, in <module> print(f.readlines()) io.UnsupportedOperation: not readable
The same will occur with the "a"
(append) mode.
How can we solve this? To be able to read a file and perform some other functioning in the same program, yous need to add the "+"
symbol to the way, similar this:
f = open("information/names.txt", "w+") # Read + Write
f = open("data/names.txt", "a+") # Read + Suspend
f = open("data/names.txt", "r+") # Read + Write
Very useful, right? This is probably what you volition 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 Files
To remove a file using Python, you need to import a module called os
which contains functions that collaborate with your operating system.
💡 Tip: A module is a Python file with related variables, functions, and classes.
Particularly, you need the remove()
role. This role takes the path to the file as argument and deletes the file automatically.
Let'south see an case. We want to remove the file chosen sample_file.txt
.
To do information technology, nosotros write this code:
import bone os.remove("sample_file.txt")
- The showtime line:
import os
is called an "import statement". This statement is written at the top of your file and it gives you access to the functions defined in theos
module. - The 2d line:
os.remove("sample_file.txt")
removes the file specified.
💡 Tip: you can use an accented or a relative path.
Now that you lot know how to delete files, permit's encounter an interesting tool... Context Managers!
🔸 Meet Context Managers
Context Managers are Python constructs that will make your life much easier. Past using them, you lot don't need to remember to close a file at the end of your program and you have access to the file in the detail function of the program that you choose.
Syntax
This is an example of a context manager used to work with files:
💡 Tip: The body of the context director has to exist indented, just like nosotros indent loops, functions, and classes. If the lawmaking is not indented, it will non be considered function of the context managing director.
When the body of the context managing director has been completed, the file closes automatically.
with open("<path>", "<mode>") every bit <var>: # Working with the file... # The file is closed here!
Example
Hither's an example:
with open("data/names.txt", "r+") equally 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 body of the context director 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 information technology over again. Just wait! We accept a line that tries to read it once again, right here below:
with open("data/names.txt", "r+") as f: print(f.readlines()) print(f.readlines()) # Trying to read the file again, outside of the context manager
Allow'due south come across what happens:
Traceback (most recent call final): File "<path>", line 21, in <module> print(f.readlines()) ValueError: I/O operation on closed file.
This error is thrown considering we are trying to read a closed file. Crawly, 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 yous're working with files, errors can occur. Sometimes yous may not accept the necessary permissions to change or admission a file, or a file might non even exist.
As a programmer, you need to foresee these circumstances and handle them in your program to avert sudden crashes that could definitely impact the user experience.
Let's run across some of the most common exceptions (runtime errors) that you might discover when you 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're trying to open doesn't exist in your electric current working directory:
f = open("names.txt")
Yous will encounter this error:
Traceback (near contempo call concluding): File "<path>", line 8, in <module> f = open("names.txt") FileNotFoundError: [Errno ii] No such file or directory: 'names.txt'
Let'southward pause this fault down this line by line:
-
File "<path>", line 8, in <module>
. This line tells you that the error was raised when the code on the file located in<path>
was running. Specifically, whenline eight
was executed in<module>
. -
f = open("names.txt")
. This is the line that caused the mistake. -
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 letters, right? This is a huge advantage during the process 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 performance without the acceptable access rights - for example filesystem permissions.
This exception is raised when y'all are trying to read or modify a file that don't take permission to access. If you try to do then, yous volition see this error:
Traceback (most recent call last): File "<path>", line eight, 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 you attempt to open or work on a directory instead of a file, and then be really careful with the path that y'all pass equally argument.
How to Handle Exceptions
To handle these exceptions, you tin use a effort/except statement. With this statement, you can "tell" your program what to do 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 jump to this block
Here you lot can see an example with FileNotFoundError
:
effort: f = open up("names.txt") except FileNotFoundError: print("The file doesn't exist")
This basically says:
- Effort to open the file
names.txt
. - If a
FileNotFoundError
is thrown, don't crash! Simply impress a descriptive statement for the user.
💡 Tip: Y'all can choose how to handle the situation by writing the appropriate code in the except
cake. Perhaps yous could create a new file if it doesn't be already.
To close the file automatically after the job (regardless of whether an exception was raised or not in the endeavor
block) y'all can add together the finally
block.
try: # Effort to run this code except <exception>: # If this exception is raised, stop the process immediately and leap to this block finally: # Do this after running the code, even if an exception was raised
This is an case:
endeavor: f = open("names.txt") except FileNotFoundError: print("The file doesn't be") finally: f.close()
In that location are many ways 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 try
block.
💡 Tip: To larn more about exception handling in Python, y'all may like to read my article: "How to Handle Exceptions in Python: A Detailed Visual Introduction".
🔸 In Summary
- You tin create, read, write, and delete files using Python.
- File objects have their own ready of methods that you lot can use to work with them in your program.
- Context Managers help yous work with files and manage them past closing them automatically when a task has been completed.
- Exception handling is cardinal in Python. Common exceptions when you are working with files include
FileNotFoundError
,PermissionError
andIsADirectoryError
. They can be handled using try/except/else/finally.
I actually hope yous liked my article and found it helpful. Now you tin work with files in your Python projects. Check out my online courses. Follow me on Twitter. ⭐️
Learn to code for free. freeCodeCamp'south open source curriculum has helped more than than twoscore,000 people become 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 "Read a Customers Status Name and Phone Number From a File Called Potentials.txt"
Enviar um comentário