DEV Community

oladejo abdullahi
oladejo abdullahi

Posted on • Updated on

how to read a file in python

How to open and read file using python.

Some time we want to open another file with our python so as to get some data which my be needed in our codes. But before we move in to that

What is file?

Before we explain how to handle files in Python, it’s important to understand what exactly a file is and how operating systems handle them.

In a simple words, a file is a contiguous set of bytes used to store data. This data is organized in a specific format and can be anything as simple as a text file or as complicated as a program executable. In the end, these byte files are then translated into binary 1 and 0 for easier processing by the computer.

Files are usually composed of three main parts:

  • Header: this is the metadata about the contents of the file (file name, )size, type, and so on)
  • Data: contents of the file or everything written by the creator of the file
  • End of file (EOF): special character that indicates the end of the file (e.g html,css,py,csv etc.). Now that we have understand what File is let's quickly go into the topic.

How to Open and Close File in Python

When you want to work with a file, the first thing to do is to open it.The key function for working with files in Python is the open() function.

The open() function: this is one of python built in functios that takes two parameters; filename, and mode. it is used to open a file for use in python.

There are four different methods (modes) for opening a file:

"r" - Read -It is the Default value for open function mode.it Opens a specified file for reading and raise error if the file does not exist.

"a" - Append - it is used to open a file for appending i.e it is use to add more content to the file. it creates the file if it does not exist.

"w" - Write - it is use to open a file for writing, creates the file if it does not exist. Note: this mode will deleted all the content in the file before writing and start a new content if the file exist.

"x" - Create - Creates the specified file, returns an error if the file exists

In addition you can specify if the file should be handled as binary or text mode by the addition of the following to the mode

"t" - Text - Default value. Text mode

"b" - Binary - Binary mode (e.g. images)
Reading from files
Suppose we have a text file called example1.txt whose contents are shown below, and we want to open the file for reading and print what is in it.
example1.txt>>

Hi everyone.
This is a text file.
let's use it in python.
Bye!
Enter fullscreen mode Exit fullscreen mode

Our code will be :

Example1

example1file=open('example1.txt') #Notice we don't need to write the mode as it is read at default
Enter fullscreen mode Exit fullscreen mode

with the code above we just open a file for reading we can read it now and use the content in it.
what if we need to write into the file how will it look like ? well just do the same thing and specify the mode

Example2

example1file=open('example2.txt','w') # we just creat and open a new file for writing as example2 is not existing before.
Enter fullscreen mode Exit fullscreen mode

the example above will open a new file for you you don't even need to have example2.txt in your folder but immediately you write the code above the file will be created although its content will be empty for now as we have not written anything yet. You can check it in your folder to confirm it.
what if we had written example1.txt instead? well since i already have it in my folder before it will still be there but the content I showed in the beginging will be wiped off so I would have empty content in my example1.txt you too can check with any of your existing file that is not important to you.
let's see anothere example of special moded. let say we need to open image with the name myimage.png How dow we do with that? well it is simple we just add the binary mode to its mode.

Example3

example1file=open('myimage.png','rb') # the 'r' is for reading while the b is to specify that it is birnary not text.
Enter fullscreen mode Exit fullscreen mode

let's see last example on this with html file.
let say we have an html file name mylist.html containing the following content.
html>>

<!DOCTYPE html>
<html>
<head>
<title>list</title>
</head>
<body>
<ol>
<li>this is number one on the list</li>
<li>this is the second number on the list</li>
</ol>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Now let's try to open it with the following code

Example4

myHtml_file=open('mylist.html','a') # ready to append or accept additional content.
Enter fullscreen mode Exit fullscreen mode

Example5

### Example2
myJson_file = open('your_json_file.json')# Your file must be in the same directory /folder of this your python file.
Enter fullscreen mode Exit fullscreen mode

Example6

myCsv_file = open('your_csv_file.csv')# Your file must be in the same directory /folder of this your python file.
Enter fullscreen mode Exit fullscreen mode

Example7

myExcel_file = open('your_Excel_file.xlsx')# Your file must be in the same directory /folder of this your python file.
Enter fullscreen mode Exit fullscreen mode

so, I believe you have understand how to open any file either text,html,csv,xlsx,python or png etc. just use the same way and you are done. Also here you should able to specify the mode depending on what you are willing to do.

How to close file when done with the content.

When you’re manipulating a file, there are two ways to close a file these are:

  • Try-finally block Method: This method is involve error handling you use 'try' to write all the codes to manipulate your data then finally will be the place to close the file. this method will automatically close the file even when encountering an error. Your code pattern look like below:
    file = open('myText_file.txt')
    try:
    # Further file processing goes here
    finally:
    file.close()
Enter fullscreen mode Exit fullscreen mode
If you’re unfamiliar with what the try-finally block you can just remove the `try` and `finally` or just use second method.
Enter fullscreen mode Exit fullscreen mode
  • Statement Method:
with open('myText_file.txt') as myText_file: #this is the same thing as 
# myText_file=open('myText_file.txt')
    # Further file processing goes here
Enter fullscreen mode Exit fullscreen mode

In this second method there is no need of close() to be use again. when you code for manipulation is done the file is close automatically.

read file in python

You already learn how to open file specific purpose, in which one of them is read. so let's see how we can read file and print them out in python.
To read file there are two method which can be use they are:

list comprehension :this method is used to load the file line-by-line into as it is written in the file.
Using list comprehension we will have the content of the text file on our python as list with respect to the line in the text file.

Example1

AllContent = [line.strip() for line in open('example1.txt')]
print(AllContent)
Enter fullscreen mode Exit fullscreen mode

Result>>

['Hi everyone.','This is a text file.','let's use it in python,Bye!]
Enter fullscreen mode Exit fullscreen mode

Example2.

example1File=open('examp1.txt')
AllContent=[] #list of all content line by line
for line in example1File: # read each of the line
    AllContent.append(line)
print(AllContent)
example1File.close()
Enter fullscreen mode Exit fullscreen mode

Result>>

['Hi everyone.\n', 'This is a text file.\n', "let's use it in python.\n", 'Bye!']
Enter fullscreen mode Exit fullscreen mode

Example3.

example1File=open('example1.txt')
for line in example1File: # read each of the line
    print(line)
example1File.close()
Enter fullscreen mode Exit fullscreen mode

Result>>

Hi everyone.

This is a text file.

let's use it in python.

Bye!
Enter fullscreen mode Exit fullscreen mode

The three example above shows how list could be use to read file. example1 and example2 are very similar only that one will printed the newline(\n) with it while the other don't. the third example is a direct way of reading and printing file in python.
Note also the that the string method strip in example1 is used to remove any whitespace characters(\nd) from the beginning and end of a string. If we had not used it, each line would contain a newline character at the end of the line just like in example2. the same thing for example2 if we had written append(line.strip()) instead of append(line) then we won't have the new line character printed.
Now let's take a look at the second method

  • string Load: This method loads the entire file into a string and can be easily printed. let take a look at some examples.

Examples1:

example1File= open('example1.txt').read()
print(example1File)
Enter fullscreen mode Exit fullscreen mode

Result>>

Hi everyone.
This is a text file.
let's use it in python.
Bye!
Enter fullscreen mode Exit fullscreen mode

Example2

mylistFile = open('mylist.html').read()
print(mylistFile)

Enter fullscreen mode Exit fullscreen mode

Result>>

<!DOCTYPE html>
<html>
<head>
<title>list</title>
</head>
<body>
<ol>
<li>this is number one on the list</li>
<li>this is the second number on the list</li>
</ol>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

all examples that we had been doing they are all in the same folder or directory as our python file but what if the file we want to open is in different directory? well just specify the directory and your code will be like.

homeFile = open(r'C:\Users\alfa\youngscience\hello.txt').read()
print(homeFile)
Enter fullscreen mode Exit fullscreen mode
Hello world!
how are you doing with your programming?
I hope you are getting it?
Enter fullscreen mode Exit fullscreen mode

the same method used in the last example can work for others too. Note the r before the directory always write it so that your programs don't raise error.
I hope you learn something consider to follow so that you don't miss the next lesson. By God's grace in the next lesson we shall be dealing with how to write and append into a file. see you in the next lesson.

Top comments (1)

Collapse
 
hb profile image
Henry Boisdequin

Nice article!