Reputation: 41
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
Upvotes: 3
Views: 2154
Reputation: 10090
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.
Upvotes: 1