#csv #python ## Reading a CSV File The most common way to read a CSV file involves the **`csv.reader`** function. 1. **Open the file:** Use a `with open(...)` statement. This ensures the file is automatically closed, even if errors occur. Use the mode `'r'` for reading. 2. **Create a reader object:** Pass the opened file object to `csv.reader()`. 3. **Iterate:** Loop through the `reader` object to process each row. Each row will be returned as a **list of strings**. Python ```python import csv def read_csv_example(filename): with open(filename, mode='r', newline='') as file: reader = csv.reader(file) header = next(reader) # Read the header row print(f"Header: {header}") print("Data Rows:") for row in reader: # 'row' is a list like ['101', 'Alice', 'Smith', 'Marketing', '65000'] print(row) # Example usage (assuming 'data.csv' exists) # read_csv_example('data.csv') ``` --- ## Writing to a CSV File Writing to a CSV file uses the **`csv.writer`** function. 1. **Open the file:** Use `with open(...)` with the mode `'w'` for writing. If you want to add to an existing file, use mode `'a'` (append). Use the argument `newline=''` to prevent extra blank rows from appearing in the output file. 2. **Create a writer object:** Pass the opened file object to `csv.writer()`. 3. **Write data:** - Use **`writer.writerow(row_list)`** to write a single row (a list). - Use **`writer.writerows(list_of_rows)`** to write multiple rows at once. Python ```python import csv def write_csv_example(filename): # Sample data header = ['Name', 'Age', 'City'] data = [ ['Peter', 30, 'London'], ['Anna', 24, 'Paris'], ['Mark', 35, 'Berlin'] ] with open(filename, mode='w', newline='') as file: writer = csv.writer(file) # Write the header writer.writerow(header) # Write the data rows writer.writerows(data) # Example usage # write_csv_example('output.csv') # print("output.csv has been created.") ``` --- ### Alternative: Using the `pandas` Library For working with large datasets, **`pandas`** is the standard tool. - **Reading:** Use `pandas.read_csv('filename.csv')` to load the data directly into a **DataFrame** (a tabular data structure). - **Writing:** Use `dataframe.to_csv('filename.csv', index=False)` to save a DataFrame to a file.