|
| 1 | +# Reading and Writing CSV Files in Python |
| 2 | + |
| 3 | +This folder provides the code examples for the Real Python tutorial [Reading and Writing CSV Files in Python](https://realpython.com/python-csv/). |
| 4 | + |
| 5 | +Consider creating a [Python virtual environment](https://realpython.com/python-virtual-environments-a-primer/) before installing the dependencies: |
| 6 | + |
| 7 | +```shell |
| 8 | +$ python3 -m venv .venv/ --prompt python-csv |
| 9 | +$ source .venv/bin/activate |
| 10 | +(python-csv) $ python -m pip install -r requirements.txt |
| 11 | +``` |
| 12 | + |
| 13 | +The scripts read their data files from the current working directory, so run them from inside this folder: |
| 14 | + |
| 15 | +```shell |
| 16 | +(python-csv) $ python read_csv_with_reader.py |
| 17 | +``` |
| 18 | + |
| 19 | +Each script holds the code from one section of the tutorial: |
| 20 | + |
| 21 | +| File | Tutorial section | |
| 22 | +| --- | --- | |
| 23 | +| `read_csv_with_reader.py` | Reading CSV Files With `csv` | |
| 24 | +| `read_csv_into_dictionary.py` | Reading CSV Files Into a Dictionary With `csv` | |
| 25 | +| `write_csv_with_writer.py` | Writing CSV Files With `csv` | |
| 26 | +| `write_csv_from_dictionary.py` | Writing CSV File From a Dictionary With `csv` | |
| 27 | +| `read_csv_with_pandas.py` | Reading CSV Files With `pandas` | |
| 28 | +| `write_csv_with_pandas.py` | Writing CSV Files With `pandas` | |
| 29 | + |
| 30 | +The examples that the tutorial shows at the interactive prompt are included in |
| 31 | +`read_csv_with_pandas.py` as `print()` calls, in the same order as the article, |
| 32 | +so that you can run the whole section as a single script. |
| 33 | + |
| 34 | +There are also three data files used throughout the tutorial: |
| 35 | + |
| 36 | +| File | Description | |
| 37 | +| --- | --- | |
| 38 | +| `employee_birthday.csv` | Employee names, departments, and birthday months read by the `csv` examples. | |
| 39 | +| `employee_addresses.csv` | Addresses containing an embedded comma, used to illustrate the optional `reader` parameters. | |
| 40 | +| `hrdata.csv` | Employee hire dates, salaries, and sick days read by the `pandas` examples. | |
| 41 | + |
| 42 | +Running the writing examples creates `employee_file.csv`, `employee_file2.csv`, |
| 43 | +and `hrdata_modified.csv` in this folder. Those files aren't checked in, since |
| 44 | +the tutorial generates them. |
0 commit comments