我终于得到了我的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'
这就是我对输出文件中奇怪间距的意思:
答案 0 :(得分:2)
您将分隔符设置为双倍空格:
contentsWrite = csv.writer(writefile, dialect='excel', delimiter=' ')
对于Excel,请不要设置分隔符,或者如果需要制表符而不是逗号,请使用excel-tab
dialect。
您也不应该将writer.writerows()
与平面列表一起使用;每个字符都写为单个列。最好的情况是,如果您希望newvarlist
中的每个元素都是一个单独的行,则只为一列生成每行的单独列表:
contentsWrite.writerows([col] for col in newvarlist)