在哪里设置更新 CSV 文件的循环?
Posted
技术标签:
【中文标题】在哪里设置更新 CSV 文件的循环?【英文标题】:Where to set loop for updating CSV file? 【发布时间】:2022-01-15 13:19:48 【问题描述】:Python 新手;任何有关格式、简单性、鼓舞人心的建议,不胜感激。
尝试编写一个脚本来搜索 CSV 中的 ID,更新同一 CSV 中该项目的记录,然后循环访问其他 ID。
如果我将“for this_item”循环放在“open with”命令中,嵌套的“for row”循环不会再次运行。我认为这是因为读取迭代已经被使用过一次。如果我在“打开方式”命令周围放置“for this_item”循环,我会得到:“ValueError: I/O operation on closed file”。
此外,这将用于多达 4,000 行和多达 30 列的 CSV - 我是否应该担心发生的重写量?
from datetime import date
from tempfile import NamedTemporaryFile
import csv
import shutil
data = [['SKU', 'Color', 'Season', 'Angles', 'Delivered'], ['A1234', 'Red', 'Week 1', 'On-model, Pinup'], ['B4321', 'Black', 'Week 2', 'On-model'], ['JJ4567', 'Blue-Multi', 'Week 1', 'Pinup'], ['ClassicTee', 'Pink', 'Week 3', 'On-model, Pinup, Detail']]
fields = data[0]
# Write Demo CSV
with open('SKU_test.csv', 'w') as csv_file_write:
csv_writer = csv.writer(csv_file_write, delimiter=',')
for row in data:
csv_writer.writerow(row)
test_csv = 'SKU_test.csv'
temp_file = NamedTemporaryFile(mode='w', delete=False)
today = date.today()
search_items = ['B4321', 'A1234']
for this_item in search_items:
with open('SKU_test.csv', 'r') as csv_file, temp_file:
reader = csv.DictReader(csv_file, fieldnames=fields)
writer = csv.DictWriter(temp_file, fieldnames=fields)
# reader_lists = list(reader)
# print(reader_lists[1])
for row in reader:
print(row['SKU'])
if row["SKU"] == str(this_item):
print(f'Search match: row')
row['Delivered'] = str(today)
writer.writerow(row)
shutil.move(temp_file.name, test_csv)
【问题讨论】:
您真的需要遍历搜索项吗?为什么不在单个循环中检查当前项目是否在search_items
中?
if row["SKU"] in search_items:
【参考方案1】:
只需为所有搜索项处理一次文件,而不是循环搜索项。
search_items = 'B4321', 'A1234'
with open('SKU_test.csv', 'r') as csv_file, NamedTemporaryFile(mode='w', delete=False) as temp_file:
reader = csv.DictReader(csv_file, fieldnames=fields)
writer = csv.DictWriter(temp_file, fieldnames=fields)
# reader_lists = list(reader)
# print(reader_lists[1])
for row in reader:
print(row['SKU'])
if row["SKU"] in search_items:
print(f'Search match: row')
row['Delivered'] = str(today)
writer.writerow(row)
shutil.move(temp_file.name, test_csv)
【讨论】:
以上是关于在哪里设置更新 CSV 文件的循环?的主要内容,如果未能解决你的问题,请参考以下文章