Python:当输出一个列表到一个csv,每个行元素添加了奇怪的间距
我终于得到了我的python程序输出我想要到csv的第1行的每个单元格,但奇怪的制表符或间距发生在每个项目Python:当输出一个列表到一个csv,每个行元素添加了奇怪的间距
这里的代码有问题的片段:
def createvars(filename, count, varlist): # Appends each suffix to each variable
varsuffix = list()
newvarlist = list()
iterations = 0
os.system('cls')
print 'Variable Creation\n-----------------'
print 'Selected file: ', filename + '\n'
try:
iterations = input('How many iterations of the variables do you need?: ')
except NameError:
print 'Please enter an interger value greater than 0'
os.system('pause')
createvars(filename, count, varlist)
for i in range(iterations):
varsuffix.append(raw_input('Variable Suffix ' + str(i+1) + ': '))
newvarlist = ['{}_{}'.format(a, b) for b in varsuffix for a in varlist]
writecsv(filename, newvarlist)
def writecsv(filename, newvarlist): # Writes to selected CSV file
with open(filename+'_output.csv', 'wb') as writefile:
if writefile.closed:
print 'ERROR: Failed to open file'
os.system('pause')
menu(0)
contentsWrite = csv.writer(writefile, dialect='excel', delimiter=' ')
contentsWrite.writerows(newvarlist)
writefile.close
print 'File saved as: ' + filename + '_output.csv'
这里是我的意思大概在输出文件怪异的间距:
要设置分隔符是一个双重空间:
contentsWrite = csv.writer(writefile, dialect='excel', delimiter=' ')
对于Excel,没有设置分隔符,或使用excel-tab
dialect如果您需要的标签,而不是逗号。
你也不应该使用writer.writerows()
与平面清单;每个字符被写为一个单独的列。在最好的,如果你想在newvarlist
每个元素是一个单独的行,产生独立列出了只用一列的每一行:
contentsWrite.writerows([col] for col in newvarlist)
我得到一个_csv错误: 文件 “variables.py”,线路112,在writecsv contentsWrite = csv.writer(WriteFile的,方言= 'excel_tab') _csv.Error:未知dialect' – 2014-08-29 15:09:12
@RussellE:所述对象名为'csv.excel_tab';如果您使用的是字符串名称,那么使用带有短划线的“excel-tab”。 – 2014-08-29 15:12:15
啊,愚蠢的错误。你会提出什么建议,而不是使用writer.writerows()作为平面列表? – 2014-08-29 15:18:29
为什么你写的字符串的平面列表以'writer.writerows() '?实际上,Excel实际上设法产生了一些有意义的东西,这实际上是相当神奇的。 – 2014-08-29 15:07:29
* Aside *:1)您不需要检查'writefile.closed',它将永远不会在'open()'后立即成为'True'。根据[文档](https://docs.python.org/2/library/functions.html#open),“*如果文件无法打开,则引发IOError。*”。 2)如果你想关闭这个文件,你可以调用'writefile.close()',而不是'writefile.close'('.close',不包含parens,什么也不做)。 3)您不需要关闭文件。一旦'with'缩进块完成,它将自动关闭。 – 2014-08-29 15:13:14