Learn How to Read Text, CSV, and JSON Files in Python
How to Easily Read Files in Python (Text, CSV, JSON)
Reading files in Python is an essential programming skill. Text, CSV, and JSON files are all commonly used for storing data and are ubiquitous across development teams. Each file type has its own advantages and disadvantages. Understanding how to read each of these file formats is critical for working with data in Python.
Reading Text Files
Text files are the most basic type of file for Python. They contain only text and line breaks. Python provides a built-in open() function that accepts two parameters; a file name as a string, and a mode as a string. The 'r' mode specifies that the file should be opened in read-only mode:
f = open('myFile.txt', 'r')
Once the file is open, you can use the read() method to read the contents of the file into a string. This string can then be converted into a list of strings, each representing a line in the file:
lines = f.read().split('\n')
To close the file handle, you can use the close() method:
f.close()
Reading CSV Files
CSV files are comma-separated values. They are usually used to store tabular data such as spreadsheets or databases. Python provides a csv module to read CSV files. To read a CSV file, you need to first import the csv module, then open the CSV file using the open() function:
import csv
f = open('myFile.csv', 'r')
You can then use the reader() function to read the contents of the CSV file into a list of lists:
csvData = csv.reader(f)
rows = list(csvData)
To close the file handle, you can use the close() method:
f.close()
Reading JSON Files
JSON files are JavaScript Object Notation. They are commonly used to store data in an organized and easy-to-access manner. Python provides a json module to read JSON files. To read a JSON file, you need to first import the json module, then open the JSON file using the open() function:
import json
f = open('myFile.json', 'r')
You can then use the load() method to read the contents of the JSON file into a dict object:
data = json.load(f)
To close the file handle, you can use the close() method:
f.close()
Conclusion
Reading files in Python is a fundamental skill that enables developers to work with data more efficiently. There are several file formats commonly used for storing data, including text, CSV, and JSON. Being familiar with each format and knowing how to read each of them is a key skill for any Python developer.