DEV Community

Cover image for Learning Python- Intermediate course: Day 37, File handling in Python
Aatmaj
Aatmaj

Posted on

Learning Python- Intermediate course: Day 37, File handling in Python

Today we cover File-handling in Python in a lightning fast speed


Many times we need to save data into files for long-term usage. Today we will learn how to write data into a file and retrieve it.

Opening a file

Python has two types of files, text and binary. But we will now learn only about text files, which are quite popular.

How will the interpreter know when to end a line? Each line in a file has the EOL terminating character (example comma or newline character) which the interpreter reads and processes a new line..

We can open a file into four modes

  • "r" Reading mode
  • "w" Writing mode
  • "a" Appending mode
  • "r+" Both reading and writing

If not passed, then Python will assume it to be “ r ” by default.

Syntax for opening a file We can open a file using the syntax

file = open('myfile.txt', 'r') # Reading mode
file = open('myfile.txt', 'a') # Writing mode
file = open('myfile.txt', 'w') # Appending mode
file = open('myfile.txt', 'r+') # Both reading and writing
Enter fullscreen mode Exit fullscreen mode

Note than the file name is case sensitive. So myfile.txt is not equal to Myfile.txt

Reading from a file

First we make a file named....say myfile.txt

A Quick brown fox jumps over the lazy dog
Welcome to PYTHON Programming
Enter fullscreen mode Exit fullscreen mode

In case the file doesn't exist, we get this error-

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    file = open("myfile.txt", "r") 
FileNotFoundError: [Errno 2] No such file or directory: 'myfile.txt'

Enter fullscreen mode Exit fullscreen mode

We can read the contents of the file using the file.read() method

file = open("myfile.txt", "r") 
print (file.read())
Enter fullscreen mode Exit fullscreen mode

OUTPUT

A Quick brown fox jumps over the lazy dog
Welcome to PYTHON Programming

Enter fullscreen mode Exit fullscreen mode

We can also return a specific number of characters by adding parameters to the read method. For example

file = open("myfile.txt", "r") 
print (file.read(7))
Enter fullscreen mode Exit fullscreen mode

OUTPUT

A Quick
Enter fullscreen mode Exit fullscreen mode

The value returned is a string

file = open("myfile.txt", "r") 
print (type(file.read(7)))
Enter fullscreen mode Exit fullscreen mode
<class 'str'>
Enter fullscreen mode Exit fullscreen mode

We can access the file line by line using the for in loop

file = open("myfile.txt", "r") 
for temp in file:
    print (temp)
Enter fullscreen mode Exit fullscreen mode

This syntax prints out each element of the file in lines.

A Quick brown fox jumps over the lazy dog

Welcome to PYTHON Programming

Enter fullscreen mode Exit fullscreen mode

Writing into a file

When we write into a file, we do not need to create one. If the file in which we want to write doesn't exist, it gets automatically created.

file = open('myfile.txt','w')
file.write("A Quick brown fox jumps over the lazy dog.")
file.write("Welcome to PYTHON Programming")
file.close()
Enter fullscreen mode Exit fullscreen mode

OUTPUT (myfile.txt)

A Quick brown fox jumps over the lazy dog.Welcome to PYTHON Programming
Enter fullscreen mode Exit fullscreen mode

The close() command terminates all the resources in use and frees the system of this particular program.

If we want the text into two separate lines, we can use the newline \n symbol.

file = open('myfile.txt','w')
file.write("A Quick brown fox jumps over the lazy dog.")
file.write("\n")
file.write("Welcome to PYTHON Programming")
file.close()
Enter fullscreen mode Exit fullscreen mode

OUTPUT- (myfile.txt)

A Quick brown fox jumps over the lazy dog.
Welcome to PYTHON Programming
Enter fullscreen mode Exit fullscreen mode

The write method overrides the file each and every time the file is opened function is called. To avoid this, we can use the append mode to add to the file.

file = open('myfile.txt','a')
file.write("A Quick brown fox jumps over the lazy dog.")
file.write("\n")
file.write("Welcome to PYTHON Programming")
file.close()
Enter fullscreen mode Exit fullscreen mode
A Quick brown fox jumps over the lazy dog.
Welcome to PYTHON ProgrammingA Quick brown fox jumps over the lazy dog.
Welcome to PYTHON Programming
Enter fullscreen mode Exit fullscreen mode

So friends we have covered file handling today. From next parts onwards we will cover object oriented programming.

Discussion (4)

Collapse
xtofl profile image
xtofl

Now we've seen the basic ingredients, it's time to abandon them and use the much safer with block (and the Path class and the writelines function)

home = Path.home()  # works on windows/linux/mac/...
lines =  ("that quick brown fox", "jumps over")
with Path(home / 'myfile.txt').open('a') as file:
    file.writelines(lines)
    file.write("1 + 2 " + 3 + " = " + 1+2+3)   # terrible TypeError here
Enter fullscreen mode Exit fullscreen mode

Adding fallible code in a with block ensures that the file gets flushed and closed, exception or not.

Collapse
aatmaj profile image
Aatmaj Author

Thanks for that. I wish I had more time for this course so I could clearly explain everything in depth. Things like exception handling, more file methods and binary files afe left unfinished. But unfortunately I will require to finish up the intermediate part of the course this week. Hope one day I will write about this all. Thanks once again for the insightful piece of code.

Collapse
xtofl profile image
xtofl

You're welcome. I appreciate the effort you put into this, but I'm not sure if I agree with your telling aspiring programmers to adopt a way that has proven to cause expensive problems: improper cleanup of opened resources (files, sockets, database connections, ...). This open/close paradigm relies entirely on developer discipline. It was common in the 1990s, but since the advent of functional programming, this can be handled by our languages and libraries.

In this specific case, consider what is easier to learn

  • 'you always have to close your file (and I won't tell you how to make sure it happens)`, or
  • 'you open a file by using a with x.open() as f: block (and safety is built-in for you)?

This may sound harsh, but I'm appealing to your responsibility as a teacher. And given the fact that I have to spend time unteaching my young colleagues' bad habits, after fixing their bugs, I feel entitled to bring this message.

You may also find this message, amongst others, repeated in this terrific talk by one of the most experienced C++ teachers: Stop Teaching C.

But again: it's really great that you take the time to write all of this down! Keep up the good work!

Thread Thread
aatmaj profile image
Aatmaj Author

Thanks for the advice👍