Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:将列表输出到csv时,每个行元素都添加了奇怪的间距_Python_Csv - Fatal编程技术网

Python:将列表输出到csv时,每个行元素都添加了奇怪的间距

Python:将列表输出到csv时,每个行元素都添加了奇怪的间距,python,csv,Python,Csv,我终于让我的python程序将我想要的输出到csv第1行的每个单元格中,不管每个项目后出现多么奇怪的制表符或间距 下面是有问题的代码段: def createvars(filename, count, varlist): # Appends each suffix to each variable varsuffix = list() newvarlist = list() iterations = 0 os.system('cls') pr

我终于让我的python程序将我想要的输出到csv第1行的每个单元格中,不管每个项目后出现多么奇怪的制表符或间距

下面是有问题的代码段:

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,不要设置分隔符,如果需要制表符而不是逗号,请使用

您也不应该将
writer.writerows()
与平面列表一起使用;每个字符都写为一个单独的列。充其量,如果您希望
newvarlist
中的每个元素都是一个单独的行,请为每一行生成单独的列表,其中只包含一列:

contentsWrite.writerows([col] for col in newvarlist)

为什么要用
writer.writerows()
编写一个简单的字符串列表?事实上,Excel成功地从中产生了一些有意义的东西是非常神奇的。旁白:1)你不需要检查
writefile.closed
,它永远不会在
open()
之后立即成为
True
。根据“如果文件无法打开,将引发IOError”。2) 如果要关闭文件,可以调用
writefile.close()
,而不是
writefile.close
.close
,不使用参数,不执行任何操作)。3) 您不需要关闭该文件。缩进块完成后,
with
将自动关闭。我得到一个_csv错误:文件“variables.py”,第112行,writecsv contentsWrite=csv.writer(writefile,dialogue='excel_tab')_csv.error:未知方言`@RussellE:对象名为
csv.excel_tab
;如果您使用的是字符串名称,则使用带破折号的
'excel-tab'
。啊,愚蠢的错误。对于平面列表,您建议使用writer.writerows()来代替它吗?@RussellE:使用
writerows()
是可以的,但请确保您按列表顺序传递。如何生成这些列表并不重要,我在这里使用了一个生成器表达式。