Reading and Writing files in Python

You always have to read and write files when working for a company or Hackathon. So, it’s necessary to know how to read different types of files.

Let’s start the boring but important part

The most important command to open a file in Python is the open() method. It takes two parameters, Name of the file and action mode.

Like most of the other programming languages, Python has 4 modes to access a file:-
1. “r” – Read – Reads a file
2. “a” – Append – Appends a file or create a new file
3. “w” – Write – Writes a new file
4. “x” – Create – Creates the specified file

Apart from these you can also specify the format in which you want to open the file:
1. t for Text(Default)
2. b for Binary file

Open a file
x = open(“Analytics.txt”,”rt”)
It opens the file, basically reads it in text format

Read the file

You can also read the file line by line by the following method or by using readline() method

Write something in a file

Delete a file

Use the “os” package and then run the remove() command
import os
os.remove(“file name”)

God forbid, if you ever have to delete a folder and want to look cool in front of your friends, you can use the following command

os.rmdir(“Name of directory”)

Reading CSV file
Comma Separated Values or CSV file format is one of the most used file formats and you will definitely come across reading a csv file often.
In order to read it, you should ideally import pandas library

import pandas as pd
x = pd.read_csv(“File Path”)

P.S. – This will convert the file in a Data Frame

You can read about different parameters here

There are a lot of file formats, but we covered only those which are of utmost important. In case you need more information, try this link from Data Camp or you can trust your best friend StackOverFlow đŸ˜›

If you need information about a specific file format, do comment below.

Keep learning đŸ™‚


Leave a Reply

Your email address will not be published. Required fields are marked *