作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我需要读取 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/
我是一名优秀的程序员,十分优秀!