Python-将CSV格式化数据写入具有可变文件名的CSV



python 3.6。

新的Python ...第一篇文章是温柔的...

我不能围绕这个...如标题中所述,我有CSV格式化的数据,我需要将其写入具有可变文件名的CSV文件。

当前我的代码使用适当的文件名创建CSV,并将数据写入CSV,,但是数据是每行的1个字母

代码看起来像:

import csv
filename = os.environ['USERPROFILE'] + 'DownloadsSomefolder\'+ variablefilename + '.csv'
myfile = open(filename, 'w', newline='')
     with myfile:
          writer = csv.writer(myfile)
          writer.writerows(csvformatteddata.decode('utf-8'))
#csvformatteddata was generated prior to this code.

任何帮助都将不胜感激,但是如果可能的话,我想用"解决方案"代码进行解释。

我希望学习/成长,而不是启用我的无知。

writerows正在期望包含每一行数据的迭代物质,其中"内部"迭代的i元素是a的i列的内容。看起来csvformatteddata是一个字符串。(我猜它看起来像a,b,cnd,e,fn...。(

要详细说明,您在每行上获得一个字符的原因是,一个长字符串本身就是迭代的迭代 - 在字符串上介绍,并且您可以在该字符上获得单个字符并迭代该字符以获得相同的角色特点。因此每个字符变成"行"。

这对我有用。

In [1]: import csv
In [2]: with open('text.csv', 'r') as old_file:
   ...:     with open('new.csv', 'w') as new_file:
   ...:         reader = csv.reader(old_file)
   ...:         writer = csv.writer(new_file)
   ...:         writer.writerows(reader)
   ...:
In [3]:

由于您的数据是一个字符串,因此应如csv模块文档中所述将其分为行。

如果您自己构造了字符串,请不要那样做。只需让CSV作者处理定界符和新线。

因此,对于csv.writer,您的数据应该看起来像这样:

[['a', 'b', 'c'], ['d', 'e', 'f']]

这样,您应该能够编写CSV文件即可:

$ python3
>>> import csv
>>> csvformatteddata = [['a','b','c'], ['d', 'e', 'f']]
>>> myfile = open('test.csv', 'w')
>>> writer = csv.writer(myfile)
>>> writer.writerows(csvformatteddata)
>>> myfile.close()
^D
$ cat test.csv
a,b,c
d,e,f

最新更新