如何在每行的末尾添加逗号

时间:2014-12-12 03:08:44

标签: python mysql file-io

我正在尝试将一行(它是一些值的列表)写入文本文件。我在每一行的末尾都需要逗号。这是为了我将每行中的信息推送到数据库中的任务。该行确实需要与我上面写的完全相同,即前面的数字和末尾的数字不能是字符串。

这就是我用来实际写入文件的行。我需要的格式是:

6,"字在这里","另一个字在这里",0,\ n

编辑:这是我目前使用的代码。 opensFile是一个csv文件。

try:
    reader = csv.reader(openedFile)
    writer = csv.writer(outputFile,delimiter=',')
    lines = []
    for row in reader:
        temp = []
        category = row[14]
        slug = slugger(category).lower()
        lines.append([termIDCount,category,slug,0])
        termIDCount += 1

    for line in lines:
        writer.writerow(line)

finally:
    openedFile.close()

2 个答案:

答案 0 :(得分:1)

一个非常简单的方法:

termIDCount = 6
category = "word here"
slug = "another word here"
lines = []
lines.append([termIDCount,category,slug,0])

for line in lines:
    s = '(' + str(line[0])
    for i in line[1:]:
        s += ',' + str(i)
    s += '),'
    print(s)
    #writer.writerow(line)

编辑:

termIDCount = 6
category = "word here"
slug = "another word here"
lines = []
lines.append([termIDCount,category,slug,0])

for line in lines:
    s = '(' + str(line[0])
    for i in line[1:]:
        if( type(i) == str ):
            s += ',"' + str(i) + '"'
        else:
            s += ',' + str(i)
    s += '),'
    print(s)
    #writer.writerow(line)

答案 1 :(得分:1)

我认为它可以很简单:

termIDCount = 6
category = "word here"
slug = "another word here"
lines = []
lines.append(','.join([str(termIDCount),category,slug,str(0)]))

with open('./foofile.csv','w') as f:
    for l in lines:
         f.write('('+l+'),\n')

如果你需要它们作为列表,那么这些行的“穿线”也可以在for循环中进一步完成。

相关问题