Handling Files in Python

A file is used to store your data. The data in file would persist even after the program is no longer running. In this tutorial, you will learn about the basic of file handling to read and to write the following file format

A file usually have three things in common:

  1. file name
  2. file extension
  3. path

File name can be any alphanumerical character and it must start with a string character. File extension indicates the type of file such as .docx for Microsoft Word document, .mp3 for music, .mp4 for movie, .txt for text file, .json for JSON file, .csv for CSV file and so on. File path represent the drive and folders (or directory) where the file is stored. On Windows, path separator are written using backslash (\) while on Linux or Mac OS path are written using slash (/)

Python has standard module called os, which is very useful for handling file. To use it, you need to import it first.

Read and Write Text File

Read and Write CSV

When you have data (either a lits, dictionary or pandas data frame table), writing it into comma delimited format would make a text file with file extension .csv. Python has standard module csv to handle reading and writing CSV format. To use it, you need to import it first

List and CSV

We can write a Python list into CSV and read it back as Python list.

Dictionary and CSV

We can write a dictionary into CSV and read it back as dictionary.

Pandas data frame and CSV

We can write a Pandas data frame table into CSV and read it back as data frame.

Read and Write JSON

JSON is popular data format, which is very similar to nested dictionary or nested list in Python. Python has json module as part of standard modules.

List and JSON

Dictionary and JSON

Pandas and JSON

Let us use the previous dataframe

References