Interview question
How do you read and write JSON and CSV files in Python? Python में JSON और CSV files कैसे read और write करें?
Answer
# JSON - using the built-in json module
import json
data = {'name': 'John', 'age': 30, 'active': True}
# Writing JSON to a file
with open('user.json', 'w') as f:
json.dump(data, f, indent=2) # indent makes it human-readable
# Reading JSON from a file
with open('user.json', 'r') as f:
loaded = json.load(f)
print(loaded['name']) # John
# Converting between JSON string and Python object without a file
json_string = json.dumps(data) # dict -> JSON string
parsed = json.loads(json_string) # JSON string -> dict
# CSV - using the built-in csv module
import csv
# Writing CSV
with open('users.csv', 'w', newline='') as f: # newline='' avoids extra blank rows
writer = csv.writer(f)
writer.writerow(['name', 'age']) # header
writer.writerow(['John', 30])
writer.writerow(['Jane', 25])
# Reading CSV
with open('users.csv', 'r') as f:
reader = csv.reader(f)
header = next(reader) # skip header row
for row in reader:
print(row) # ['John', '30']
# DictReader/DictWriter - work with rows as dictionaries (uses header automatically)
with open('users.csv', 'r') as f:
dict_reader = csv.DictReader(f)
for row in dict_reader:
print(row['name'], row['age']) # John 30# JSON - built-in json module
import json
data = {'name': 'John', 'age': 30, 'active': True}
# JSON file में लिखना
with open('user.json', 'w') as f:
json.dump(data, f, indent=2)
# JSON file पढ़ना
with open('user.json', 'r') as f:
loaded = json.load(f)
print(loaded['name']) # John
# बिना file के string convert करना
json_string = json.dumps(data)
parsed = json.loads(json_string)
# CSV - built-in csv module
import csv
with open('users.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['name', 'age'])
writer.writerow(['John', 30])
with open('users.csv', 'r') as f:
reader = csv.reader(f)
header = next(reader)
for row in reader:
print(row)
# DictReader - dictionaries की तरह
with open('users.csv', 'r') as f:
dict_reader = csv.DictReader(f)
for row in dict_reader:
print(row['name'], row['age'])Was this answer clear?