Skip to content

Commit dabb74e

Browse files
authored
Merge pull request #498 from manuothatceguy/feat/add-csv-cheatsheet
feat: add csv module with examples of basic usage and reference to Python docs
2 parents f5553dc + 791332a commit dabb74e

File tree

3 files changed

+158
-1
lines changed

3 files changed

+158
-1
lines changed

contributors/contributors.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,5 +81,6 @@
8181
"pyxfluff",
8282
"pranayat",
8383
"prashanthbhat203",
84-
"QuarkZ26"
84+
"QuarkZ26",
85+
"manuothatceguy"
8586
]

docs/modules/csv-module.md

Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
---
2+
title: Python Csv Module - Python Cheatsheet
3+
description: Python has a csv module, which allows us to work easily with CSV files.
4+
---
5+
6+
<base-title :title="frontmatter.title" :description="frontmatter.description">
7+
Python Csv Module
8+
</base-title>
9+
10+
The csv module provides tools to read from and write to CSV files, which are commonly used for data exchange.
11+
12+
<base-disclaimer>
13+
<base-disclaimer-title>
14+
csv Module vs Manual File Read-Write
15+
</base-disclaimer-title>
16+
<base-disclaimer-content>
17+
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.
18+
<br>
19+
For more on file handling basics, see the <router-link to="/cheatsheet/file-directory-path">File and directory Paths</router-link> page.
20+
</base-disclaimer-content>
21+
</base-disclaimer>
22+
23+
To get started, import the module:
24+
```python
25+
import csv
26+
```
27+
28+
## csv.reader()
29+
30+
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:
31+
32+
```python
33+
import csv
34+
35+
file_path = 'file.csv'
36+
37+
with open(file_path, 'r', newline='') as csvfile:
38+
reader = csv.reader(csvfile)
39+
40+
for line in reader:
41+
print(line)
42+
```
43+
44+
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).
45+
46+
## csv.writer()
47+
48+
This function receives the file to be written as a csv file, similar to the reader function, it should be invoked as this:
49+
50+
```python
51+
import csv
52+
53+
file_path = 'file.csv'
54+
55+
with open(file_path, 'w', newline='') as csvfile:
56+
writer = csv.writer(csvfile)
57+
58+
# do something
59+
```
60+
61+
The "do something" block could be replaced with the use of the following functions:
62+
### writer.writerow()
63+
64+
Writes a single row to the CSV file.
65+
66+
```python
67+
writer.writerow(['name', 'age', 'city'])
68+
writer.writerow(['Alice', 30, 'London'])
69+
```
70+
71+
### writer.writerows()
72+
73+
Writes multiple rows at once.
74+
75+
```python
76+
rows = [
77+
['name', 'age', 'city'],
78+
['Bob', 25, 'Paris'],
79+
['Carol', 28, 'Berlin']
80+
]
81+
writer.writerows(rows)
82+
```
83+
84+
## csv.DictReader
85+
86+
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.
87+
88+
```python
89+
import csv
90+
91+
with open('people.csv', 'r', newline='') as csvfile:
92+
reader = csv.DictReader(csvfile)
93+
for row in reader:
94+
print(row['name'], row['age'])
95+
```
96+
97+
- Each `row` is an `OrderedDict` (or a regular `dict` in Python 3.8+).
98+
- If your CSV does not have headers, you can provide them with the `fieldnames` parameter:
99+
```python
100+
reader = csv.DictReader(csvfile, fieldnames=['name', 'age', 'city'])
101+
```
102+
103+
## csv.DictWriter
104+
105+
Lets you write dictionaries as rows in a CSV file. You must specify the fieldnames (column headers) when creating the writer.
106+
107+
```python
108+
import csv
109+
110+
fieldnames = ['name', 'age', 'city']
111+
rows = [
112+
{'name': 'Alice', 'age': 30, 'city': 'London'},
113+
{'name': 'Bob', 'age': 25, 'city': 'Paris'}
114+
]
115+
116+
with open('people_dict.csv', 'w', newline='') as csvfile:
117+
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
118+
writer.writeheader() # writes the header row
119+
writer.writerows(rows)
120+
```
121+
122+
- Use `writer.writeheader()` to write the column headers as the first row.
123+
- Each dictionary in `writer.writerows()` must have keys matching the `fieldnames` specified when creating the writer.
124+
125+
## Additional params to csv.reader() and csv.writer()
126+
127+
### delimiter
128+
129+
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.
130+
131+
```python
132+
import csv
133+
134+
with open('data_semicolon.csv', newline='') as csvfile:
135+
reader = csv.reader(csvfile, delimiter=';')
136+
for row in reader:
137+
print(row)
138+
```
139+
140+
### lineterminator
141+
142+
Character or sequence of characters to end a line. Most common is "\r\n" but it could be "\n".
143+
144+
### quotechar
145+
146+
Character used to quote fields containing special characters (default is `"`).
147+
148+
```python
149+
reader = csv.reader(csvfile, quotechar="'")
150+
```
151+
152+
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>.

src/store/navigation.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,10 @@ export const useNavigationStore = defineStore('navigation', {
149149
path: '/modules/copy-module',
150150
updated: false,
151151
},
152+
{
153+
name: 'Csv',
154+
path: '/modules/csv-module'
155+
},
152156
{
153157
name: 'Datetime',
154158
path: '/modules/datetime-module',

0 commit comments

Comments
 (0)