Navigation

Reading from a Text File Reading from a CSV File Reading from a JSON File Reading Text File Data Writing to a Text File Appending to a Text File

File I/O Operations

1. Reading from a Text File

with open('filename.txt', 'r') as infile: lines = infile.readlines() for line in lines: print(line)

2. Reading from a CSV File

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

import json with open('filename.json', 'r') as infile: data = json.load(infile) for item in data: print(item)

4. Reading Text File Data

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

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

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