Python: how to read files

Python like many other languages has built in commands to interact with files, lets see how they work.

Python: how to read files
Photo by Jamie Street on Unsplash
Join Medium with my referral link - Konstantinos Patronas
Read every story from Konstantinos Patronas (and thousands of other writers on Medium). Your membership fee directly…

Python like many other languages has built in commands to interact with files, lets see how they work.

Create the following file and save it as t1.txtline1
line2
line3

Now to open a file with python we use the open command$ python
Python 3.8.10 (default, Mar 15 2022, 12:22:08)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> file = open("t1.txt")

To print a single line we use the readline() function>>> print(file.readline())
line1>>>

If we run again the readline() function will print the next line until the end of the file>>> print(file.readline())
line2>>> print(file.readline())
line3>>> print(file.readline())>>>

To read the whole file at once we can use the read() function>>> file = open("t1.txt")
>>> print(file.read())
line1
line2
line3

Now since we finished our work with the file we can now close the file using the close() function.>>> file.close()
>>>

The reason behind closing files are

  • Not to exhaust the the open file descriptors of the OS
  • Not to create race-conditions between processes that try to read / write files

You can avoid the open/use/close pattern when you work with files by using the with keyword>>> with open("./t1.txt") as file:
...   for line in file:
...     print(line)
...
line1line2line3

When we use open within the with the file closes automatically when exits the block of commands.

Did you noticed that each line printed with an additional new-line after each line? this is because the print method added an additional new-line, how we can avoid this? we can use the strip() function>>> with open("./t1.txt") as file:
...   for line in file:
...     print(line.strip())
...
line1
line2
line3

You now might have start wondering why iterate each line and not store the whole line to a variable and do whatever i want? well using the read() function can be a good or bad idea depending on the file size! if the file is really big it might consume our whole memory in order to store it in a variable , if is a small file then its a good idea!, personally i prefer to iterate a file line by line because even in case that i have to work with a file that is really big and i did not expect a really big file there is no danger to exhaust the memory of my computer.

Thats all for now! i hope you found this article useful :)

Join Medium with my referral link - Konstantinos Patronas
Read every story from Konstantinos Patronas (and thousands of other writers on Medium). Your membership fee directly…