csv file operations
This commit is contained in:
60
src/intermediate/json_csv/csv_file.py
Normal file
60
src/intermediate/json_csv/csv_file.py
Normal 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()
|
||||||
3
src/intermediate/json_csv/output.csv
Normal file
3
src/intermediate/json_csv/output.csv
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
Name,Age,City
|
||||||
|
|
||||||
|
Alice,25,New York
|
||||||
|
3
src/intermediate/json_csv/output2.csv
Normal file
3
src/intermediate/json_csv/output2.csv
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
Name,Age,City
|
||||||
|
Alice,25,New York
|
||||||
|
Bob,30,Los Angeles
|
||||||
|
Reference in New Issue
Block a user