Skip to content

Commit 50a45d3

Browse files
Add Csv module documentation and update contributors list
1 parent 1cebfe1 commit 50a45d3

File tree

3 files changed

+152
-1
lines changed

3 files changed

+152
-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: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
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+
This function receives the file to be written as a csv file, similar to the reader function, it should be invoked as this:
48+
49+
```python
50+
import csv
51+
52+
file_path = 'file.csv'
53+
54+
with open(file_path, 'w', newline='') as csvfile:
55+
writer = csv.writer(csvfile)
56+
57+
# do something
58+
```
59+
60+
The "do something" block could be replaced with the use of the following functions.
61+
### writer.writerow()
62+
Writes a single row to the CSV file.
63+
64+
```python
65+
writer.writerow(['name', 'age', 'city'])
66+
writer.writerow(['Alice', 30, 'London'])
67+
```
68+
69+
### writer.writerows()
70+
Writes multiple rows at once.
71+
72+
```python
73+
rows = [
74+
['name', 'age', 'city'],
75+
['Bob', 25, 'Paris'],
76+
['Carol', 28, 'Berlin']
77+
]
78+
writer.writerows(rows)
79+
```
80+
81+
## csv.DictReader
82+
83+
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.
84+
85+
```python
86+
import csv
87+
88+
with open('people.csv', 'r', newline='') as csvfile:
89+
reader = csv.DictReader(csvfile)
90+
for row in reader:
91+
print(row['name'], row['age'])
92+
```
93+
94+
- Each `row` is an `OrderedDict` (or a regular `dict` in Python 3.8+).
95+
- If your CSV does not have headers, you can provide them with the `fieldnames` parameter:
96+
```python
97+
reader = csv.DictReader(csvfile, fieldnames=['name', 'age', 'city'])
98+
```
99+
100+
## csv.DictWriter
101+
102+
Lets you write dictionaries as rows in a CSV file. You must specify the fieldnames (column headers) when creating the writer.
103+
104+
```python
105+
import csv
106+
107+
fieldnames = ['name', 'age', 'city']
108+
rows = [
109+
{'name': 'Alice', 'age': 30, 'city': 'London'},
110+
{'name': 'Bob', 'age': 25, 'city': 'Paris'}
111+
]
112+
113+
with open('people_dict.csv', 'w', newline='') as csvfile:
114+
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
115+
writer.writeheader() # writes the header row
116+
writer.writerows(rows)
117+
```
118+
119+
- Use `writer.writeheader()` to write the column headers as the first row.
120+
- Each dictionary in `writer.writerows()` must have keys matching the `fieldnames` specified when creating the writer.
121+
122+
## Additional params to csv.reader() and csv.writer()
123+
124+
### delimiter
125+
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.
126+
127+
```python
128+
import csv
129+
130+
with open('data_semicolon.csv', newline='') as csvfile:
131+
reader = csv.reader(csvfile, delimiter=';')
132+
for row in reader:
133+
print(row)
134+
```
135+
136+
### lineterminator
137+
Character or sequence of characters to end a line. Most common is "\r\n" but it could be "\n".
138+
139+
### quotechar
140+
Character used to quote fields containing special characters (default is `"`).
141+
142+
```python
143+
reader = csv.reader(csvfile, quotechar="'")
144+
```
145+
146+
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)