avatarAli

Summarize

How To Handle Files With Python Like a Pro

Easy follow guide to delete, read, and write to a file using Python

Photo by Sara Kurfeß on Unsplash

File handling is one of the most important and used skills. Its popularity can be seen with the fact that it is required while doing any type of practical application with Python(like Web Scrapping, Data Science, or Web Applications). And yet it is often ignored while learning Python, but not anymore!

With this basic skill, you will be able to open, edit and manipulate endless file formats. For eg you will be able to manipulate popular formats like:

  1. Comma-separated values (CSV)
  2. ZIP
  3. Plain Text (txt)
  4. JSON
  5. XML
  6. HTML
  7. Images
  8. PDF
  9. DOCX
  10. MP3
  11. MP4

keep in note that in this article we will primarily focus on .txt files, but the methods used here will also be used for other formats as well. So lets get into the real deal!

1. How to open files

To open a file, it's quite straightforward and easy, just use the inbuilt Python open() function.

If the file is present in the current directory, then just the file name is enough. Python will look at that file in the same folder. Otherwise, if the file is present other than the current directory, a complete path of that file is required.

In the below code, mode specifies what needs to be done with the file and how it should be opened.

file = open(name, mode)

Below is the list of modes that are frequently used, there are a few others also which I haven’t mentioned below because they aren’t that popularly used.

1. r: Read opens a file for reading only. (default)
2. w: Write opens a file for writing only, deleting earlier contents
3. a: Append opens a file for appending.

Eg.

f=open("scrap.txt","w")

The above line of code will open the scrap.txt file present in the current directory, with the write-only mode. If there is any file present already with the name scrap.txt, it will be deleted, and a new file with the given name will be created.

If you don't want the already file to be deleted, a is the right option to go.

note: If nothing is given in the mode argument, then by default it is set to r

2. How to read files

To read the contents of a file, you must open it first.

f=open("scrap.txt")
print(f.read())

note: We use read() function because, the open function just stores the path and other setting of the file, not the content.

If you try to print the f variable without using the read function, you would get the following in your console log, which is primarily details of the files rather than contents.

<_io.TextIOWrapper name=’scrap.txt’ mode=’r’ encoding=’UTF-8'>

There is another method to view the contents of the file, with better control, which is by looping through each line of the file.

f=open("scrap.txt")

for line in f:
    print(line)

3. How to write into a file

To write in the file, you must either use the write w or append a as the method.

f=open("scrap.txt","w")
f.write("This is how you can use Python to write data in files")
f.close()

Tip: To add a new empty line, you can use \n character inside the code. This will add an empty line, otherwise, you will quickly find everything jumbled up.

f.write("This is how you can use Python to write data in files\n")
f.write("Added a new line")

4. How to close files in Python

It is important to close the file once you are done using it, as closing the file will free up all the resources the file was using previously.

f=open("scrap.txt","w")
f.close()

5. How do delete a file

To delete a file, you must import the Python OS module.

import os
os.remove(“scrap.txt”)

Conclusion

In this article, we saw how to open, read, write, and delete a file using Python. With this skill, the possible use cases are endless as almost everything deals with manipulating files. Be it web scrapping, automation, web application, etc…

Thank you and I hope you liked this article :)

Python
Programming
Data Science
Software Development
Software Engineering
Recommended from ReadMedium