Pages

Friday, February 26, 2021

Python File Operation

 Open() Function

To work with files in Python, we need to use the open() function. There are three options to work with files:

Read (r): This is the default option which opens a file to read.
Write (w): Open a file and write to it. Overwrites any current content in the file.
Append (a): Opens the file and writes to it but instead of overwriting, appends to the file.
Python can work with text or binary (JPG, PNG, MP3, etc.) files.

Open File

I’ll create a text file named “demo.txt” with the following contents:
text_file = open("demo.txt")
print(text_file.read())

In our code, we didn’t specify whether we wanted to read, write, or append to the file. We also didn’t specify whether we wanted to open it in text or binary mode. We don’t have to because the default options are “r” (read) and “t” (text). If you do want to specify our options, it looks like this:

text_file = open("demo.txt", "rt")

print(text_file.read())

So far, so good. We have the contents of our file. However, Python returned it as a string. Wouldn’t it be easier if each line was a separate string? We can do this with the readlines() function:

text_file = open("demo.txt")

print(text_file.readlines())

Close File

In the example above, we opened a file but we never closed it. Closing files is important, especially when you write files.  Some changes in files won’t show up until you close them. In Microsoft Windows, open files are locked which prevents other programs from opening or writing to your files. Here’s an example of how to close your file:

text_file = open("demo.txt")
print(text_file.readlines())
text_file.close()

With Open

Instead of using the separate open() and close() function, we can also use the with block. You put everything you want to do with the file under the with block, and afterward, Python automatically closes the file. Here is an example:

with open("demo.txt") as text_file:
    lines = text_file.readlines()    
print(lines)


Write File

When you write to a file, you overwrite its contents. When the file doesn’t exist, Python creates the file. To write to the file, we need to add the “w” parameter to the open() function. Here is our code:

with open("demo2.txt", "w") as text_file:
    text_file.write("Writing content to this file")
with open("demo2.txt") as text_file:
    lines = text_file.readlines()    
print(lines)

The code above writes a string to the “demo2.txt” file. We could use a text editor to check the contents of the file but since we are using Python, we’ll open it in Python as well.

If you run this code multiple times, it always shows a single line. That’s because the write parameter overwrites the content of our file.

Append File

Instead of overwriting the content of our file, we can append to the file. To do this, you have to use the “a” parameter in the open() function:

with open("demo2.txt", "a") as text_file:
    text_file.write("Writing content to this file")
with open("demo2.txt") as text_file:
    lines = text_file.readlines()

print(lines)

When we run the above code multiple times, you’ll see that Python appends the string to our file. There is one problem though. Python appends the string to the same line.

New Line

If you want to append to a new line, you have to use the \n new line symbol in your string. Here’s our code:

with open("demo2.txt", "a") as text_file:
    text_file.write("\nWriting content to this file")

with open("demo2.txt") as text_file:

    lines = text_file.readlines()   

print(lines)

In the code above, I added the \n new line symbol before my string. Each line we append is now saved in a new line of our file.

Delete File

What if we want to delete a file? We can do this with the OS module and the os.remove() function. This doesn’t work on the embedded Python interpreter so you might want to try this on your own computer. Here is the code:

import os
os.remove("demo2.txt")
or 
import os
file_to_delete = "demo2.txt"
if os.path.exists(file_to_delete):
    os.remove(file_to_delete)
else:
  print("File does not exist.")

No comments:

Post a Comment