简体   繁体   中英

python : how to variables many strings in one line in csv file

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()

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

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