csvwriter

Python - csv writer - writing lists to csv file, how to exclude "[]" and quotes?


The code below works and writes the necessary information, but the output includes the symbols [], '' How can I edit the code to exclude these items.

above5 = []
    with open(path,"r") as file_to_be_read:
        csv_reader = csv.reader(file_to_be_read)
    
        header = next(csv_reader)
        #print(header)
        for line in csv_reader:
            if float(line[7]) >=5:
                above5.append(line)
            
    with open ("Python_Practice/cerealdata.csv", "w") as file_to_be_written:
            file_to_be_written.write(str(header) + "\n")
            for x in range(len(above5)):
                file_to_be_written.write(str(above5[x]) + "\n")

OUTPUT:

OUTPUT


Solution

  • Use csv.writer to write the rows you want. The writer will take a list like the list you get from the reader and convert it to a CSV row. No need for an intermediate list, you can open the writer and write row by row. Note the use of .writerows with a generator that filters out the rows you don't want.

    with open(path, newline="") as file_to_be_read:
        csv_reader = csv.reader(file_to_be_read)
        with open("Python_Practice/cerealdata.csv", "w", newline="") as file_to_be_written:
            csv_writer = csv.writer(file_to_be_written)
            csv_writer.writerow(next(csv_reader))
            csv_writer.writerows(row for row in csv_reader if float(line[7]) >=5)