简体   繁体   中英

Write to csv file column instead of row in python

I am trying to write to column (A,B,C etc) of csv file instead of row. Here is the code I am trying: With this I am able to write in column A. In the next if condition, I want to add if the rec values are >10 and < 20 then print in Column B. I tried something like this in commented code, but it is writing to rows not column. There might be big work around doing this, but any easy and neater way please? Thanks! (The num_file.txt contains 100 numbers randomly generated, values between 0 and 100 )

    import csv
    l =[]
    with open("num_file.txt", "r") as ipfile, open("op1.csv", "w") as opfile:
        reader = csv.reader(ipfile)
        writer = csv.writer(opfile)
        for rec in reader:
          for i in range(len(rec)):
             if float(rec[i]) < 10:            
               l.insert(0,[rec[i]])
             #if float(rec[i]) > 10 and float(rec[i]) < 20:
             #  l.insert(1,[rec[i]])
        writer.writerows(l)

The CSV file output is now like this:

4.57

2.1

7.05

8.05

3.27

8.9

5.45

8.74

4.55

The output csv file

You should just write a single row with writer.writerow(l) . If you use writerows(l) you'll write a row for each element in l , which is why you have one element per row.

Here are the csv.writer docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM