Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion contributors/contributors.json
Original file line number Diff line number Diff line change
Expand Up @@ -81,5 +81,6 @@
"pyxfluff",
"pranayat",
"prashanthbhat203",
"QuarkZ26"
"QuarkZ26",
"manuothatceguy"
]
152 changes: 152 additions & 0 deletions docs/modules/csv-module.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
---
title: Python Csv Module - Python Cheatsheet
description: Python has a csv module, which allows us to work easily with CSV files.
---

<base-title :title="frontmatter.title" :description="frontmatter.description">
Python Csv Module
</base-title>

The csv module provides tools to read from and write to CSV files, which are commonly used for data exchange.

<base-disclaimer>
<base-disclaimer-title>
csv Module vs Manual File Read-Write
</base-disclaimer-title>
<base-disclaimer-content>
While you can read and write CSV files using basic file operations and string methods (like <code>open()</code> with <code>read</code> or <code>write</code> and <code>split()</code>), the <code>csv</code> module is designed to handle edge cases such as quoted fields, embedded delimiters, and different line endings. It ensures compatibility with CSV files generated by other programs (like Excel) and reduces the risk of parsing errors. For most CSV tasks, prefer the <code>csv</code> module over manual parsing.
<br>
For more on file handling basics, see the <router-link to="/cheatsheet/file-directory-path">File and directory Paths</router-link> page.
</base-disclaimer-content>
</base-disclaimer>

To get started, import the module:
```python
import csv
```

## csv.reader()

This function receives a file which needs to be an [iterable of strings](https://docs.python.org/3/library/csv.html#id4:~:text=A%20csvfile%20must%20be%20an%20iterable%20of%20strings%2C%20each%20in%20the%20reader%E2%80%99s%20defined%20csv%20format). In other words, it should be the open file as it follows:

```python
import csv

file_path = 'file.csv'

with open(file_path, 'r', newline='') as csvfile:
reader = csv.reader(csvfile)

for line in reader:
print(line)
```

This function returns a reader object which can be easily iterated over to obtain each row. Each column in the corresponding rows can be accessed by the index, without the need to use the built-in function [`split()`](https://www.pythoncheatsheet.org/cheatsheet/manipulating-strings#split).

## csv.writer()

This function receives the file to be written as a csv file, similar to the reader function, it should be invoked as this:

```python
import csv

file_path = 'file.csv'

with open(file_path, 'w', newline='') as csvfile:
writer = csv.writer(csvfile)

# do something
```

The "do something" block could be replaced with the use of the following functions:
### writer.writerow()

Writes a single row to the CSV file.

```python
writer.writerow(['name', 'age', 'city'])
writer.writerow(['Alice', 30, 'London'])
```

### writer.writerows()

Writes multiple rows at once.

```python
rows = [
['name', 'age', 'city'],
['Bob', 25, 'Paris'],
['Carol', 28, 'Berlin']
]
writer.writerows(rows)
```

## csv.DictReader

Allows you to read CSV files and access each row as a dictionary, using the first row of the file as the keys (column headers) by default.

```python
import csv

with open('people.csv', 'r', newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
print(row['name'], row['age'])
```

- Each `row` is an `OrderedDict` (or a regular `dict` in Python 3.8+).
- If your CSV does not have headers, you can provide them with the `fieldnames` parameter:
```python
reader = csv.DictReader(csvfile, fieldnames=['name', 'age', 'city'])
```

## csv.DictWriter

Lets you write dictionaries as rows in a CSV file. You must specify the fieldnames (column headers) when creating the writer.

```python
import csv

fieldnames = ['name', 'age', 'city']
rows = [
{'name': 'Alice', 'age': 30, 'city': 'London'},
{'name': 'Bob', 'age': 25, 'city': 'Paris'}
]

with open('people_dict.csv', 'w', newline='') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader() # writes the header row
writer.writerows(rows)
```

- Use `writer.writeheader()` to write the column headers as the first row.
- Each dictionary in `writer.writerows()` must have keys matching the `fieldnames` specified when creating the writer.

## Additional params to csv.reader() and csv.writer()

### delimiter

Should be the character used to separate the fields. As the file type says, the default is the comma ','. Depending on the locale, Excel might generate csv files with the semicolon as a delimiter.

```python
import csv

with open('data_semicolon.csv', newline='') as csvfile:
reader = csv.reader(csvfile, delimiter=';')
for row in reader:
print(row)
```

### lineterminator

Character or sequence of characters to end a line. Most common is "\r\n" but it could be "\n".

### quotechar

Character used to quote fields containing special characters (default is `"`).

```python
reader = csv.reader(csvfile, quotechar="'")
```

For more details, see the <a href="https://docs.python.org/3/library/csv.html" target="_blank" rel="noopener">official Python csv module documentation</a>.
4 changes: 4 additions & 0 deletions src/store/navigation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,10 @@ export const useNavigationStore = defineStore('navigation', {
path: '/modules/copy-module',
updated: false,
},
{
name: 'Csv',
path: '/modules/csv-module'
},
{
name: 'Datetime',
path: '/modules/datetime-module',
Expand Down