Read Each Individual Line and Get Initials Python

Welcome
Hi! If you want to larn how to work with files in Python, so this commodity is for yous. Working with files is an important skill that every Python developer should learn, so let's go started.
In this article, you 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 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 be raised when you work with files.
- and more!
Allow's begin! ✨
🔹 Working with Files: Bones Syntax
One of the most important functions that you will need to employ as you work with files in Python is open up()
, a built-in function that opens a file and allows your program to apply it and work with it.
This is the bones syntax:

💡 Tip: These are the two most ordinarily used arguments to call this office. There are half-dozen boosted optional arguments. To learn more about them, please read this article 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 piece of work with.
Nosotros 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()
part.
For example, the path in this role 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 equally the Python script, like this:

Simply if the file is inside a nested folder, like this:

Then nosotros demand to use a specific path to tell the office that the file is inside another binder.
In this example, this would be the path:
open up("information/names.txt")
Notice that we are writing information/
showtime (the name of the folder followed past a /
) and then 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: Fashion
The second parameter of the open()
role is the way
, a cord with ane grapheme. That single graphic symbol basically tells Python what you are planning to practice with the file in your program.
Modes available are:
- Read (
"r"
). - Append (
"a"
) - Write (
"west"
) - Create (
"10"
)
You can also choose to open the file in:
- Text way (
"t"
) - Binary mode (
"b"
)
To employ text or binary mode, you would demand to add these characters to the main mode. For instance: "wb"
means writing in binary manner.
💡 Tip: The default modes are read ("r"
) and text ("t"
), which ways "open for reading text" ("rt"
), then yous don't need to specify them in open up()
if you lot want to use them considering they are assigned by default. You lot can simply write open up(<file>)
.
Why Modes?
Information technology 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 practice more than necessary? This is basically why modes be.
Remember nearly it — allowing a program to do more than necessary can problematic. For case, if y'all just need to read the content of a file, it can exist dangerous to allow your program to modify it unexpectedly, which could potentially introduce bugs.
🔸 How to Read a File
At present that yous know more than near the arguments that the open()
part takes, let's see how y'all can open a file and shop it in a variable to employ it in your program.
This is the bones syntax:

We are simply assigning the value returned to a variable. For case:
names_file = open up("data/names.txt", "r")
I know y'all might be asking: what type of value is returned by open()
?
Well, a file object.
Permit'southward talk a little chip 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 resources.
This is basically telling us that a file object is an object that lets u.s. work and interact with existing files in our Python program.
File objects have attributes, such as:
- proper name: the proper noun of the file.
- airtight:
True
if the file is airtight.False
otherwise. - style: the fashion used to open the file.

For example:
f = open up("data/names.txt", "a") print(f.style) # Output: "a"
Now let'southward see how you lot tin 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, nosotros need to have a way to "interact" with them in our program and that is exactly what methods do. Let's come across some of them.
Read()
The first method that you demand to learn almost is read()
, which returns the entire content of the file every bit a string.

Hither we have an example:
f = open up("data/names.txt") print(f.read())
The output is:
Nora Gino Timmy William
You can use the type()
function to confirm that the value returned by f.read()
is a cord:
print(type(f.read())) # Output <grade 'str'>
Yes, it'southward a cord!
In this case, the unabridged file was printed considering we did not specify a maximum number of bytes, but nosotros can practise this as well.
Hither we have an example:
f = open("information/names.txt") print(f.read(3))
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 free the resources associated to the file. To do this, you lot need to telephone call the close()
method, like this:

Readline() vs. Readlines()
Y'all can read a file line by line with these two methods. They are slightly unlike, and so let'south run into them in particular.
readline()
reads one line of the file until it reaches the stop of that line. A trailing newline grapheme (\northward
) is kept in the string.
💡 Tip: Optionally, you tin can pass the size, the maximum number of characters that y'all desire to include in the resulting string.

For example:
f = open("information/names.txt") print(f.readline()) f.close()
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 every bit individual elements (strings). This is the syntax:

For example:
f = open("information/names.txt") print(f.readlines()) f.close()
The output is:
['Nora\n', 'Gino\due north', 'Timmy\due north', 'William']
Notice that there is a \n
(newline character) at the end of each string, except the final ane.
💡 Tip: You tin can get the same list with list(f)
.
You can 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()
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 let'due south see how you lot can create files.
🔹 How to Create a File
If you need to create a file "dynamically" using Python, you can do information technology with the "x"
manner.
Let'southward run across how. This is the basic syntax:

Here's an example. This is my current working directory:

If I run this line of lawmaking:
f = open("new_file.txt", "10")
A new file with that name is created:

With this fashion, you can create a file and then write to it dynamically using methods that yous volition learn in just a few moments.
💡 Tip: The file will be initially empty until you lot alter it.
A curious thing is that if you attempt to run this line once again and a file with that proper name already exists, y'all volition see this mistake:
Traceback (most recent phone call last): File "<path>", line 8, in <module> f = open up("new_file.txt", "x") 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.
Now that you know how to create a file, let'due south meet how you can modify it.
🔸 How to Alter a File
To modify (write to) a file, you need to use the write()
method. You have two means to do it (append or write) based on the fashion that you choose to open it with. Let's come across them in detail.
Append
"Appending" means adding something to the end of another matter. The "a"
style allows you to open a file to append some content to it.
For instance, if we have this file:

And we want to add a new line to it, we can open up it using the "a"
way (append) and then, call the write()
method, passing the content that we want to append as argument.
This is the bones syntax to phone call the write()
method:

Hither's an case:
f = open("data/names.txt", "a") f.write("\nNew Line") f.close()
💡 Tip: Discover that I'grand calculation \due north
earlier the line to indicate that I want the new line to announced as a separate line, not as 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.close()
runs.
Write
Sometimes, you may want to delete the content of a file and supervene upon it entirely with new content. You can do this with the write()
method if you open the file with the "w"
mode.
Here we accept this text file:

If I run this script:
f = open("data/names.txt", "westward") f.write("New Content") f.close()
This is the result:

Every bit y'all tin can see, opening a file with the "westward"
mode and then writing to it replaces the existing content.
💡 Tip: The write()
method returns the number of characters written.
If yous want to write several lines at once, y'all can utilise the writelines()
method, which takes a listing of strings. Each string represents a line to be added to the file.
Here'south 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 yous know how to create, read, and write to a file, but what if you desire to do more than than one thing in the same program? Let'due south run into what happens if nosotros try to do this with the modes that you take learned so far:
If y'all open a file in "r"
fashion (read), and so attempt to write to it:
f = open("data/names.txt") f.write("New Content") # Trying to write f.shut()
You will get this error:
Traceback (well-nigh recent call concluding): File "<path>", line 9, in <module> f.write("New Content") io.UnsupportedOperation: non writable
Similarly, if yous open a file in "westward"
mode (write), and and so try to read it:
f = open("data/names.txt", "w") print(f.readlines()) # Trying to read f.write("New Content") f.close()
Y'all will see this mistake:
Traceback (most contempo call final): File "<path>", line 14, in <module> print(f.readlines()) io.UnsupportedOperation: not readable
The same will occur with the "a"
(append) fashion.
How can we solve this? To exist able to read a file and perform another performance in the same program, you need to add together the "+"
symbol to the mode, like this:
f = open("information/names.txt", "west+") # 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 will apply in your programs, but be sure to include only the modes that you need to avert potential bugs.
Sometimes files are no longer needed. Allow's encounter how you can delete files using Python.
🔹 How to Delete Files
To remove a file using Python, you lot need to import a module chosen os
which contains functions that interact with your operating organization.
💡 Tip: A module is a Python file with related variables, functions, and classes.
Specially, yous demand the remove()
function. This function takes the path to the file every bit argument and deletes the file automatically.

Let's see an example. We desire to remove the file chosen sample_file.txt
.

To do information technology, we write this code:
import os os.remove("sample_file.txt")
- The get-go line:
import os
is chosen 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 second line:
os.remove("sample_file.txt")
removes the file specified.
💡 Tip: you can use an absolute or a relative path.
Now that you know how to delete files, let's come across an interesting tool... Context Managers!
🔸 Meet Context Managers
Context Managers are Python constructs that volition brand your life much easier. By using them, you don't need to remember to close a file at the end of your plan and you accept access to the file in the item part of the programme that yous choose.
Syntax
This 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 nosotros indent loops, functions, and classes. If the code is not indented, it will non be considered function of the context manager.
When the torso of the context manager has been completed, the file closes automatically.
with open up("<path>", "<mode>") as <var>: # Working with the file... # The file is closed hither!
Example
Here's an example:
with open("data/names.txt", "r+") as 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 it Once again
After the torso has been completed, the file is automatically closed, and then it can't be read without opening it again. But expect! We have a line that tries to read it again, right here below:
with open("data/names.txt", "r+") as f: print(f.readlines()) print(f.readlines()) # Trying to read the file once again, outside of the context manager
Let's see what happens:
Traceback (near recent telephone call last): 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 airtight file. Awesome, right? The context manager does all the heavy piece of work for u.s., it is readable, and curtailed.
🔹 How to Handle Exceptions When Working With Files
When yous'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 plan to avoid sudden crashes that could definitely affect the user feel.
Let's run into some of the nigh common exceptions (runtime errors) that y'all might notice when y'all piece of work with files:
FileNotFoundError
Co-ordinate to the Python Documentation, this exception is:
Raised when a file or directory is requested but doesn't exist.
For instance, if the file that you're trying to open up doesn't exist in your current working directory:
f = open up("names.txt")
You will encounter this error:
Traceback (most recent telephone call final): File "<path>", line 8, in <module> f = open("names.txt") FileNotFoundError: [Errno two] No such file or directory: 'names.txt'
Let's intermission this error down this line by line:
-
File "<path>", line 8, in <module>
. This line tells you that the fault was raised when the code 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 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 messages, right? This is a huge reward during the procedure of debugging.
PermissionError
This is some other 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 alter a file that don't have permission to admission. If you try to do so, you lot will see this error:
Traceback (most recent telephone call last): File "<path>", line eight, in <module> f = open("<file_path>") PermissionError: [Errno thirteen] 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 try to open up or work on a directory instead of a file, so be actually conscientious 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 program what to do in instance something unexpected happens.
This is the bones syntax:
endeavour: # Effort to run this code except <type_of_exception>: # If an exception of this blazon is raised, terminate the process and jump to this cake
Hither you tin can see an example with FileNotFoundError
:
try: f = open up("names.txt") except FileNotFoundError: print("The file doesn't exist")
This basically says:
- Try to open the file
names.txt
. - If a
FileNotFoundError
is thrown, don't crash! Simply print a descriptive argument for the user.
💡 Tip: You can choose 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 exist already.
To close the file automatically later on the chore (regardless of whether an exception was raised or not in the endeavor
block) yous can add together the finally
block.
try: # Try to run this lawmaking except <exception>: # If this exception is raised, stop the procedure immediately and leap to this block finally: # Do this after running the code, even if an exception was raised
This is an instance:
endeavor: f = open up("names.txt") except FileNotFoundError: print("The file doesn't be") finally: f.close()
There are many ways to customize the try/except/finally statement and y'all can even add an else
cake to run a block of lawmaking only if no exceptions were raised in the endeavour
block.
💡 Tip: To learn 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 can create, read, write, and delete files using Python.
- File objects take their own ready of methods that you can use to work with them in your plan.
- Context Managers help you work with files and manage them by closing them automatically when a task has been completed.
- Exception treatment is key in Python. Common exceptions when you are working with files include
FileNotFoundError
,PermissionError
andIsADirectoryError
. They can be handled using try/except/else/finally.
I really hope y'all 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 lawmaking for free. freeCodeCamp's open up source curriculum has helped more than twoscore,000 people get jobs as developers. Go started
johnswoperand1967.blogspot.com
Source: https://www.freecodecamp.org/news/python-write-to-file-open-read-append-and-other-file-handling-functions-explained/
Postar um comentário for "Read Each Individual Line and Get Initials Python"