3

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

1
  • how does your number file look like? e.g. comma separated numbers? Commented Dec 5, 2017 at 14:22

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Beat me too it, documentation here.
Thanks for your comment. I do not want to write one row with all elements. I want to write one element per row just as I have done. But the next thing I want to do is for the next condition, if each element is between 10 and 20, I want to write each element in a separate row just like my first writerow but in column B. I was trying it with the codes that are commented out, but that does not work, it still writes in same column A and not B

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.