In [ ]:
# Reading CSV files into a dictionary
import csv
healthcare_data = {}
with open(''''healthcare_data.csv'''', mode=''''r'''') as file:
csv_reader = csv.DictReader(file)
for row in csv_reader:
patient_id = row["patient_id"]
healthcare_data[patient_id] = {
"name": row["name"],
"age": row["age"],
"gender": row["gender"],
"diagnosis": row["diagnosis"]
}
print(healthcare_data)
In [ ]:
# Reading a CSV File with quotechar
import csv
with open(''''sample.csv'''', mode=''''r'''', newline='''''''') as file:
reader = csv.reader(file, delimiter='''','''', quotechar=''''"'''')
for row in reader:
print(row)
In [ ]:
# Writing to a CSV File with quotechar
import csv
data = [
[''''Name'''', ''''Age'''', ''''City''''],
[''''Alice'''', ''''25'''', ''''New York''''],
[''''Bob'''', ''''30'''', ''''Los Angeles''''],
[''''Charlie'''', ''''35'''', ''''Chicago'''']
]
with open(''''output.csv'''', mode=''''w'''', newline='''''''') as file:
writer = csv.writer(file, delimiter='''','''', quotechar=''''"'''', quoting=csv.QUOTE_MINIMAL)
for row in data:
writer.writerow(row)
In [ ]:
# Reading a CSV File into a pandas DataFrame
import pandas as pd
df = pd.read_csv(''''sample.csv'''', quotechar=''''"'''')
print(df)
In [ ]:
# Writing a pandas DataFrame to a CSV File
import pandas as pd
data = {
''''Name'''': [''''Alice'''', ''''Bob'''', ''''Charlie''''],
''''Age'''': [25, 30, 35],
''''City'''': [''''New York'''', ''''Los Angeles'''', ''''Chicago'''']
}
df = pd.DataFrame(data)
df.to_csv(''''output.csv'''', index=False, quotechar=''''"'''', quoting=csv.QUOTE_NONNUMERIC)