IFRAME SYNC
import csv
def read_csv(file_path):
try:
with open(file_path, 'r') as csvfile:
csvreader = csv.reader(csvfile)
for row in csvreader:
print(row)
except FileNotFoundError:
print(f"File not found: {file_path}")
except Exception as e:
print(f"An error occurred: {e}")
def write_csv(file_path, data):
try:
with open(file_path, 'w', newline='') as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerows(data)
except Exception as e:
print(f"An error occurred: {e}")
# Example usage:
data_to_write = [
['Name', 'Age', 'City'],
['John Doe', 30, 'New York'],
['Jane Smith', 25, 'Los Angeles'],
['Bob Johnson', 40, 'Chicago']
]
csv_file_path = 'example.csv'
write_csv(csv_file_path, data_to_write)
read_csv(csv_file_path)import csv
def read_csv(file_path):
try:
with open(file_path, 'r') as csvfile:
csvreader = csv.reader(csvfile)
# Read and print header
header = next(csvreader)
print("Header:", header)
# Read and print data
for row in csvreader:
print(row)
except FileNotFoundError:
print(f"File not found: {file_path}")
except Exception as e:
print(f"An error occurred: {e}")
def write_csv(file_path, data, header=None, mode='w'):
try:
with open(file_path, mode, newline='') as csvfile:
csvwriter = csv.writer(csvfile)
# Write header if provided
if header:
csvwriter.writerow(header)
# Write data
csvwriter.writerows(data)
print(f"Data successfully written to {file_path}")
except Exception as e:
print(f"An error occurred: {e}")
# Example usage:
data_to_append = [
['Alice Johnson', 35, 'San Francisco'],
['Charlie Brown', 28, 'Seattle']
]
csv_file_path = 'example.csv'
# Writing initial data
data_to_write = [
['Name', 'Age', 'City'],
['John Doe', 30, 'New York'],
['Jane Smith', 25, 'Los Angeles'],
['Bob Johnson', 40, 'Chicago']
]
write_csv(csv_file_path, data_to_write, header=True)
# Reading the initial data
read_csv(csv_file_path)
# Appending new data
write_csv(csv_file_path, data_to_append, mode='a')
# Reading the updated data
read_csv(csv_file_path)
IFRAME SYNC
Comments
Post a Comment