简体   繁体   English

在新行上将列表打印为CSV或txt

[英]Printing list to CSV or txt on new lines

I'm trying to export some data, taken from an sql database, to a txt- or csv-file. 我正在尝试将从sql数据库中获取的一些数据导出到txt或csv文件。 The print statement: 打印声明:

for x in range(len(data)):
        print(data[x]) 

this outputs what I want, every element in a new line 这会输出我想要的内容,新行中的每个元素

(1, 90, Netherlands, male)
(2,  50, Germany, Female)

etc.. Now, when I try putting this to a text file it just adds everything in 1 long line, all the info pasted behind each other just like a regular print(data) command. 现在,当我尝试将其添加到文本文件中时,它只是将所有内容添加到一条长行中,所有信息都粘贴在彼此之后,就像常规的print(data)命令一样。

I posted my code below so you get the context 我在下面发布了我的代码,以便您了解上下文

sql = 'SELECT * FROM batch'
c.execute(sql)
data = c.fetchall()
list1 = []
addDataToList = list1.append(data)
for x in range(len(data)):
    print(data[x])

    with open('Rapport.txt', mode="w") as output:
    for x in range(len(data)):
        output.write("\n" .join(str(data[x])))
sql = 'SELECT * FROM batch'
c.execute(sql)
data = c.fetchall()
list1 = []
addDataToList = list1.append(data)
for x in range(len(data)):
    print(data[x])

with open('Rapport.txt', mode="w") as output:
    for x in range(len(data)):
        print(str(data[x]), file=output) 

Every element on a new line 新行上的每个元素

Then try this 然后尝试这个

sql = 'SELECT * FROM batch'
c.execute(sql)
data = c.fetchall()
list1 = []
addDataToList = list1.append(data)
# construct output
outputString = ''
for x in range(len(data)):
   outputString = outputString + str(data[x]) + '\n'
# write output to file
with open('Rapport.txt', mode="w") as output:
   output.write(outputString)

By the way, you're writing to the same file x^2 number of times, with only the last write being visible as you keep overwriting the last write. 顺便说一句,你写的是相同的文件x^2次,只有最后一次写入是可见的,因为你一直在覆盖最后一次写入。 You should be careful with nested for statements. 你应该小心嵌套for语句。 See the example below: 请参阅以下示例:

data = ['1', '90', 'Netherlands', 'male']
result = ''
for x in range(len(data)):
    print(data[x])

    #with open('Rapport.txt', mode="w") as output:
    for x in range(len(data)):
        #output.write("\n" .join(str(data[x])))
        result = result + (data[x] + ' ')

print (str(result))

Output: 输出:

1 90 Netherlands male 1 90 Netherlands male 1 90 Netherlands male 1 90 Netherlands male 1 90荷兰男性1 90荷兰男性1 90荷兰男性1 90荷兰男性

Use write with \\n to write content to each line. 使用write with \\n将内容写入每一行。

Ex: 例如:

with open('Rapport.txt', mode="w") as output:
    for i in data:
        output.write("{0} \n".format(str(i)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM