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

时间:2018-11-25 02:16:33

标签: python python-3.x

我需要读取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)

1 个答案:

答案 0 :(得分:1)

如果您只是不想创建标题,并且可以使用空文件,那么请在洛杉矶的第一个实例之前不要创建作家。例如,除非在洛杉矶一行,否则不会将标头添加到文件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)

但是,如果除非有Los Angeles实例,否则根本不应该创建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()