简体   繁体   English

如何在cgi / python中将列表列表写入文件?

[英]How to write list of list to a file in cgi/python?

I have a list of list : 我有一个清单清单:

 table = []
 headers = ["JobId", "Name", "Start_Date", "End_Date", "Value"]
 table.append(headers)
 values1 = ['efwef', 'erwerw', '01', '02', 99]
 table.append(values1)
 values2 = ['efwsdfsef', 'erdwerw', '01']
 table.append(values2)

The table is a list of list where each list has different length of elements and all elements may be string 该表是列表的列表,其中每个列表具有不同的元素长度,并且所有元素都可以是字符串

index.cgi : index.cgi:

print "Content-Type: text/plain; charset=UTF-8"
print "Content-Disposition: attachment; filename=test.txt"
print

for row in table:
    for row_values in row:
        if type(row_values) is not str:
            row_values = str(row_values)
        print row_values + '\t'
    print '\n'

But this prints : 但这打印:

JobId
Name
Start_Date
End_Date
Value

efwef
erwerw
01
02
99

.... .... .... ....

Can some one tell me what I am doing wrong here ? 有人可以告诉我我在做什么错吗? I tried replacing '\\n' and print "#########" still I see: 我尝试替换'\\ n'并打印“ #########”,但仍然看到:

   JobId
    Name
    Start_Date
    End_Date
    Value
##########################
    efwef
    erwerw
    01
    02
    99
##########################

even though I didn't add '\\n' each element in the list is printing in a new line. 即使我没有添加'\\ n'列表中的每个元素也都在换行中打印。

print adds a newline. print会添加换行符。 One way to do what you want would be to print your lines at once using str.join (also: note that all your data are strings, so no need to convert to string) 一种执行所需操作的方法是使用str.join一次print行(另请注意:所有数据都是字符串,因此无需转换为字符串)

for row in table:
    print("\t".join(row))

if you have integers/floats that wouldn't work so: 如果您无法使用整数/浮点数,则:

for row in table:
    print("\t".join(map(str,row)))

the nice touch with join is that it doesn't add a (useless) \\t at the end of the string and you don't have to handle that manually. join是,它不会在字符串的末尾添加\\t (没用),并且您不必手动处理。

But you can do it in an even simpler way using csv module (even with lists of lists of non-strings), in one line: 但是,您可以在一行中使用csv模块(甚至包含非字符串列表的列表)以更简单的方式执行此操作:

import csv,sys

csv.writer(sys.stdout,delimiter="\t").writerows(table)

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

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