简体   繁体   English

写入csv文件列而不是python中的行

[英]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. 我试图写入csv文件的列(A,B,C等)而不是行。 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. 这是我正在尝试的代码:有了这个,我可以写在A列中。在下一个if条件中,我想添加如果rec值> 10且<20然后在B列中打印。我试过这样的事情在注释代码中,但它写入行而不是列。 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 ) (num_file.txt包含随机生成的100个数字,值介于0和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: CSV文件输出现在是这样的:

4.57 4.57

2.1 2.1

7.05 7.05

8.05 8.05

3.27 3.27

8.9 8.9

5.45 5.45

8.74 8.74

4.55 4.55

The output csv file 输出csv文件

You should just write a single row with writer.writerow(l) . 你应该用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. 如果你使用writerows(l)你会写一排中的每个元素l ,这就是为什么你必须每行一个元素。

Here are the csv.writer docs 这是csv.writer文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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