Files
Python_CookBook_repo/6.数据编码与处理/1.读写CSV数据.py
2025-09-10 16:12:45 +08:00

38 lines
1019 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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