gpt4 book ai didi

python - 在 Python 中写入空文件之前如何检查条件?

转载 作者:行者123 更新时间:2023-12-01 08:41:55 24 4
gpt4 key购买 nike

我需要读取 data.csv 中的所有行,如果 City 列的值为 Los Angeles,那么它会将该行添加到 match.csv,但我不希望它创建带有标题的 match.csv如果 data.csv 的“城市”列中没有包含洛杉矶的行,则为空行。我该怎么做?

with open("data.csv", 'r') as input_file, open("match.csv", 'w') as output_file:
data_reader = csv.DictReader(input_file)
match_write = csv.DictWriter(output_file, delimiter=',', fieldnames=data_reader.fieldnames)
match_write.writeheader()
for row in data_reader:
if row['City'] == "Los Angeles":
match_write.writerow(row)

最佳答案

如果您只是不想创建 header ,并且可以使用空文件,那么在洛杉矶的第一个实例之前不要创建编写器。例如,除非有包含 Los Angeles 的行,否则不会将 header 添加到文件 match.csv 中:

match_write = None

with open("data.csv", 'r') as input_file, open("match.csv", 'w') as output_file:
data_reader = csv.DictReader(input_file)
for row in data_reader:
if row['City'] == "Los Angeles":
if match_write is None:
match_write = csv.DictWriter(output_file, delimiter=',', fieldnames=data_reader.fieldnames)
match_write.writeheader()
match_write.writerow(row)

但是,如果除非存在洛杉矶实例,否则根本不应该创建 match.csv 文件,那么在第一个实例之前也不应打开该文件。

output_file = None

with open("data.csv", 'r') as input_file:
data_reader = csv.DictReader(input_file)
for row in data_reader:
if row['City'] == "Los Angeles":
if output_file is None:
output_file = open("match.csv", 'w')
match_write = csv.DictWriter(output_file, delimiter=',', fieldnames=data_reader.fieldnames)
match_write.writeheader()
match_write.writerow(row)

if output_file is not None:
output_file.close()

关于python - 在 Python 中写入空文件之前如何检查条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53464118/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com