Skip to content

Instantly share code, notes, and snippets.

@mridulgain
Created November 18, 2023 16:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mridulgain/cd101384e174e981592262ff521879f5 to your computer and use it in GitHub Desktop.
Save mridulgain/cd101384e174e981592262ff521879f5 to your computer and use it in GitHub Desktop.
csv file handeling using python
import csv
def write_to_csv(filename, data):
with open(filename, 'w', newline='') as csvfile:
# Create a CSV writer object
csv_writer = csv.writer(csvfile)
# Write a single row
csv_writer.writerow(["Name", "Age", "City"])
# Write multiple rows
csv_writer.writerows(data)
print(f"Data written to {filename}.")
def read_from_csv(filename):
try:
with open(filename, 'r') as csvfile:
# Create a CSV reader object
csv_reader = csv.reader(csvfile)
# Read header
header = next(csv_reader)
print("Header:", header)
# Read and print each row
for row in csv_reader:
print(row)
except FileNotFoundError:
print(f"{filename} not found.")
except Exception as e:
print(f"Error reading {filename}: {e}")
# Example usage:
filename = "example_csv_file.csv"
data_to_write = [
["John", 30, "New York"],
["Alice", 25, "San Francisco"],
["Bob", 35, "Los Angeles"]
]
# Write to a CSV file
write_to_csv(filename, data_to_write)
# Read from the CSV file
read_from_csv(filename)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment