[英]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: 我有多个变量,我需要将它们写到CSV文件中,但是CSV读取一个序列,因此它将所有字符写在一行中,并且我需要一行中的所有变量,并且它们之间要有空格变量:
pdate=30/03/2017
ptime=17:17:30
outlet1= 12345
outlet2=6789
so i want them in CSV like this: 所以我想要像这样的CSV文件:
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 ? 我设法通过将每个变量都索引到一个列表中来做到这一点,并使用“ zip”将所有列表写在一行中,但是我想看看是否还有另一种方法? 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])
只需使用
writer.writerow([pdate, ptime, outlet1, outlet2])
Note, it is writer.writerow
instead of writer.writerows
注意,它是
writer.writerow
而不是writer.writerows
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.