Working with Files in Python
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.
Ready for more? These paid resources pick up where this lesson leaves off.
Project-based python video courses — the perfect paid next step after these free lessons.
Browse on Udemy →Hand-picked python books to master the fundamentals offline.
See on Amazon →Some links on this page are affiliate links: we may earn a commission at no extra cost to you. We only recommend tools we believe are genuinely useful.