Python
/
Storage
- 1 Language 9
-
Hello World S
-
Variables S
-
Functions S
-
Conditional A S
-
Operators S
-
While S
-
Turtle S
-
Script Mode S
-
Debugging S
- 2 Strings 7
-
Slice S
-
Raw Strings S
-
Regex A S
-
Validation S
-
Config S
-
Security S
-
Encrypt A S
- 3 Collections 6
-
Lists S
-
Dictionaries S
-
Efficiency S
-
Tree S
-
Tuples S
-
References S
- 4 Functions 5
-
Recursion S
-
Factorial S
-
Modulus S
-
Reassignment S
-
Approximate S
- 5 Storage 8
-
Files S
-
Databases S
-
Pipes S
-
With open S
-
Shelve A S
-
Zip S
-
Csv S
-
Json S
- 6 Class 4
-
Definition S
-
Attributes S
-
Functional S
-
Methods S
- 7 Goodies 5
-
Conditional Expression S
-
List Comprehension A S
-
Generator S
-
Named Tuple S
-
Modules S
- 8 Applications 5
-
Pythagora A S
-
Palindrome A S
-
Binary Search A S
-
Conway Game A S
-
Coin Flip A S
- 9 Scheduler 4
-
Time S
-
Multithreading A S
-
Subprocess S
-
Logging S
- 10 Packages 6
-
Clipboard A S
-
Ocr A S
-
Socket S
-
Image S
-
Virtualenv S
-
Jupyter S
S
R
Q
Python Storage Csv
import csv with open('file.csv') as file: reader = csv.reader(file)
Reader
p371 The CSV format it's just a text file with comma-separated values.
"""CSV reader:
Always use csv module for reading and writing CSV files.
It's not enough to just split the text file by comma (,)
Maybe files use escape characters to allowed commas as part of values.
The most convenient to access values in the reader object ...
is to convert it to a list
"""
import csv, pathlib
DIR = pathlib.Path(__file__).resolve().parent
"""Convert the csv reader to a list:
"""
with open(DIR / 'data/file1.csv') as file:
reader = csv.reader(file)
data = list(reader)
assert data[0][0] == '11'
assert data[0][1] == '12'
"""With large files you'll want a for loop:
"""
with open(DIR / 'data/file1.csv') as file:
reader = csv.reader(file)
for row in reader:
print(row)
# ['11', '12', '12']
# ['21', '22', '23']
# ['31', '32', '33']
Writer
p374 Wth writer object you can write data to a CSV file.
"""CSV writer:
Use open() method and pass it 'w' argument.
On windows you'll also need to pass newline='' argument.
"""
import csv, pathlib
DIR = pathlib.Path(__file__).resolve().parent
# Writer
with open(DIR / 'data/file2.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow([11, 12, 13])
writer.writerow([21, 22, 23])
writer.writerow([31, 32, 33])
# Check
with open(DIR / 'data/file2.csv') as file:
reader = csv.reader(file)
data = list(reader)
assert data[1][1] == '22'
assert data[2][2] == '33'
Dictionary
For CSV files that contain header you can use dictionary.
"""CSV Dict:
It is often more convenient to work with ...
DictReader and DictWriter objects.
You can pass headers values as arguments.
"""
import csv, pathlib
from typing import AnyStr
DIR = pathlib.Path(__file__).resolve().parent
# Dictionary Reader
with open(DIR / 'data/fileH1.csv') as file:
dr = csv.DictReader(file)
for row in dr:
print(row['A'], row['B'], row['C'])
# 11 12 13
# 21 22 23
# 31 32 33
# Dictionary Writer
with open(DIR / 'data/fileH2.csv', 'w', newline='') as file:
dw = csv.DictWriter(file, ['A', 'B', 'C'])
dw.writeheader()
dw.writerow({'A':11, 'B':12, 'C':13})
dw.writerow({'A':21, 'B':22, 'C':23})
dw.writerow({'A':31, 'B':32, 'C':33})
# Check the file
A = []
with open(DIR / 'data/fileH2.csv') as file:
dr = csv.DictReader(file)
for row in dr:
A.append(row['A'])
print(A)
# ['11', '21', '31']
➥ Questions