csv file operations

This commit is contained in:
2025-08-24 19:42:00 +05:30
parent 0dcec244bc
commit 2981454719
3 changed files with 66 additions and 0 deletions

View File

@ -0,0 +1,60 @@
import csv
import os
def create_csv_file():
file_path = get_current_directory_path(__file__)
output_file = os.path.join(file_path, 'output.csv')
with open(output_file, 'w') as file:
writer = csv.writer(file)
writer.writerow(['Name', 'Age', 'City'])
writer.writerows([
['Alice', 25, 'New York'],
['Bob', 30, 'Los Angeles']
])
def create_csv_file2():
file_path = get_current_directory_path(__file__)
output_file = os.path.join(file_path, 'output2.csv')
with open(output_file, 'w', newline='') as file:
fieldnames = ['Name', 'Age', 'City']
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'Name': 'Alice', 'Age': 25, 'City': 'New York'})
writer.writerow({'Name': 'Bob', 'Age': 30, 'City': 'Los Angeles'})
def get_current_directory_path(file_path) -> str:
file = os.path.abspath(file_path)
current_dir = os.path.dirname(file)
return current_dir
def read_csv_row_by_row():
file_path = get_current_directory_path(__file__)
output_file = os.path.join(file_path, 'output.csv')
with open(output_file, 'r', newline='') as file:
reader = csv.reader(file) # default delimiter is comma
for row in reader:
print(row)
def read_csv_as_dict():
file_path = get_current_directory_path(__file__)
output_file = os.path.join(file_path, 'output2.csv')
with open(output_file, 'r', newline='') as file:
reader = csv.DictReader(file)
for row in reader:
print(row)
if __name__ == "__main__":
create_csv_file()
create_csv_file2()
read_csv_row_by_row()
read_csv_as_dict()

View File

@ -0,0 +1,3 @@
Name,Age,City
Alice,25,New York
1 Name Age City
2 Alice 25 New York
3 Bob 30 Los Angeles

View File

@ -0,0 +1,3 @@
Name,Age,City
Alice,25,New York
Bob,30,Los Angeles
1 Name Age City
2 Alice 25 New York
3 Bob 30 Los Angeles