File I/O Operations
1. Reading from a Text File
- Open a
.txt file in read mode using open('filename', 'r').
- Use
readlines() to read all lines into a list.
- Iterate through the list to process each line.
with open('filename.txt', 'r') as infile:
lines = infile.readlines()
for line in lines:
print(line)
2. Reading from a CSV File
- Open a
.csv file in read mode using open('filename', 'r').
- Use the
csv.reader() module to read rows as lists.
- Use
next() to skip the header row if present.
import csv
with open('filename.csv', 'r') as infile:
lines = csv.reader(infile)
next(lines) # Skip the header row
for line in lines:
print(line)
3. Reading from a JSON File
- Open a
.json file in read mode using open('filename', 'r').
- Use
json.load() to parse the JSON file into a Python dictionary or list.
import json
with open('filename.json', 'r') as infile:
data = json.load(infile)
for item in data:
print(item)
4. Reading Text File Data
- Use slicing to read specific fields from each line in a text file.
- For example, read student_id, name, and class_id based on their positions in the line.
people.txt
1. 01John Doe 24/12
2. 02Jane Smith 25/13
with open('people.txt', 'r') as infile:
lines = infile.readlines()
print(lines)
for line in lines:
student_id = line[0:2]
name = line[2:22]
classid = line[22:].strip()
print(student_id)
print(name)
print(classid)
---------------------------------------
01
John Doe
24/12
02
Jane Smith
25/13
5. Writing to a Text File
- Open a file in write mode using
open('filename', 'w').
- Use
write() to add formatted data to the file.
- Format the output using
f-strings or other string formatting methods.
with open('result.txt', 'w') as outfile:
student_id = "03"
name = 'Ali'
classid = '24/12'
outfile.write(f'{student_id}{name:20}{classid}\n')
result.txt
1. 03Ali 24/12
6. Appending to a Text File
- Open a file in append mode using
open('filename', 'a').
- Use
append() to add formatted data to a new line at the end of the file.
- Format the output using
f-strings or other string formatting methods.
with open('result.txt', 'a') as outfile:
student_id = "04"
name = 'Jack'
classid = '25/12'
outfile.write(f'{student_id}{name:20}{classid}\n')
result.txt
1. 03Ali 24/12
2. 04Jack 25/12