BeginnerCoder
intermediate#python#files#io

Working with Files in Python

This article was AI-drafted and has not been reviewed yet. Spotted a mistake? Tell us.

Learn how to read and write files in Python, including text files, CSV files, and JSON files.

Introduction to File Input/Output

In this tutorial, we will cover the basics of file input/output in Python.

Step 1: Reading a Text File

To read a text file in Python, you can use the open() function in read mode ('r').

# Example of reading a text file
file = open('example.txt', 'r')
content = file.read()
print(content)
file.close()

Step 2: Writing a Text File

To write a text file in Python, you can use the open() function in write mode ('w').

# Example of writing a text file
file = open('example.txt', 'w')
file.write('Hello, World!')
file.close()

Step 3: Reading a CSV File

To read a CSV file in Python, you can use the csv module.

# Example of reading a CSV file
import csv
with open('example.csv', 'r') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

Step 4: Writing a JSON File

To write a JSON file in Python, you can use the json module.

# Example of writing a JSON file
import json
data = {'name': 'John', 'age': 30}
with open('example.json', 'w') as file:
    json.dump(data, file)

By following these steps, you can learn how to work with files in Python and start building your own file-based projects.

Keep going with python

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.