0

I have multiple variables and I need to write them in CSV file , but CSV reads a sequences, so it writes every character in one line, and I need all of variables in one line with space separating between them For example, if I have these variables:

pdate=30/03/2017 
ptime=17:17:30 
outlet1= 12345
outlet2=6789

so i want them in CSV like this:

30/03/2017   17:17:30    12345    6789

and if I got more data, it will write them in the next line like :

30/03/2017   17:17:30    12345    6789
30/03/2017   17:19:10    34354    4335

I managed to do it by turning every variable to index inside one list and used "zip" to write all the lists in one line, but I would like to see if there is another way to do that ? here is my code

    outlet1.append(12345)
    outlet2.append(6789)
    pdate.append("30/03.2017")
    ptime.append("17:17:30")
    with open('file.csv','a') as f:
            writer = csv.writer(f,delimiter=' ');
            writer.writerows(zip(pdate,ptime,outlet1,outlet2))
        f.close()
2
  • I ziped lists, and tht works fine, but I need away to do it without using lists. Commented Mar 30, 2017 at 17:31
  • Yes, because a list with a single element that is a string is not the same thing as just the string. Look at the answer I posted. Commented Mar 30, 2017 at 17:32

1 Answer 1

2

Because you are zipping strings. When you iterate over a string, you iterate over the individual characters. Just use writer.writerow([pdate, ptime, outlet1, outlet2])

Note, it is writer.writerow instead of writer.writerows

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

1 Comment

Yes with writer.writerow worked totally fine as I wanted. I tried that command before, but I used writer.writerows

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.