2025-09-10:仓库迁移
This commit is contained in:
37
6.数据编码与处理/1.读写CSV数据.py
Normal file
37
6.数据编码与处理/1.读写CSV数据.py
Normal file
@@ -0,0 +1,37 @@
|
||||
import csv
|
||||
from collections import namedtuple
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 想要读取csv数据,可以使用csv库
|
||||
with open("6.数据编码与处理/1.stocks.csv") as f:
|
||||
f_csv = csv.reader(f)
|
||||
headers = next(f_csv)
|
||||
print(headers)
|
||||
|
||||
for row in f_csv:
|
||||
print(row)
|
||||
|
||||
# 但是这样处理就非常不妙,所有的东西混在一起,变成奇奇怪怪的样子,不如使用named_tuple
|
||||
f.seek(0)
|
||||
|
||||
Row = namedtuple("Row", headers)
|
||||
for row in f_csv:
|
||||
print(row)
|
||||
row = Row(*row)
|
||||
print(row.Symbol)
|
||||
|
||||
f.seek(0)
|
||||
f_csv = csv.DictReader(f)
|
||||
for row in f_csv:
|
||||
print(row['Symbol'])
|
||||
|
||||
# 如果想要插入一条数据,可以使用writer
|
||||
rows = [
|
||||
("BB", 123, "9/12/2024", "9:36AM", -12, 999)
|
||||
]
|
||||
|
||||
with open("6.数据编码与处理/1.stocks.csv", 'w+') as f:
|
||||
f_csv = csv.writer(f)
|
||||
f_csv.writerows(rows)
|
||||
|
||||
# 我的评价是不如pandas
|
Reference in New Issue
Block a user