intermediate#python#files#io
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.