Python_File_IO_Guide
Python_File_IO_Guide
File handling is an essential part of programming. Python provides built-in functions to read, write,
and manipulate files efficiently.
Python's `open()` function is used to open files. The basic syntax is:
file = open("filename", "mode")
Example:
file = open("example.txt", "r")
file.close()
4. Reading Files
Methods for reading files:
- `read()`: Reads the entire file.
- `readline()`: Reads one line at a time.
- `readlines()`: Reads all lines as a list.
Example:
with open("example.txt", "r") as file:
content = file.read()
print(content)
5. Writing to Files
Example:
with open("example.txt", "w") as file:
file.write("Hello, World!\n")
Appending:
with open("example.txt", "a") as file:
file.write("Appending new data.")
Reading CSV:
import csv
with open("data.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
Writing CSV:
with open("data.csv", "w", newline='') as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age"])
writer.writerow(["Alice", 25])
Writing JSON:
import json
data = {"name": "Alice", "age": 25}
with open("data.json", "w") as file:
json.dump(data, file)
Reading JSON:
with open("data.json", "r") as file:
data = json.load(file)
print(data)
try:
with open("nonexistent.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("File not found!")