写一个包含列表的文件

2024-09-24 00:31:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列表,希望将其写入一个没有“”的文件,[]

d = [['value1', 'value2', 'value3', 'value4', 'LatX', 'LonY', 'HgtZ', 'sats'],
     ['431.84', '1417', '3.63', '10.28', '47.06446389', '15.45043694', '428.08', '6'],
     ['438.25', '1416', '3.63', '10.28', '47.06446583', '15.45044000', '428.00', '6'],
     ['437.64', '1418', '3.63', '9.7', '47.06446583', '15.45044333', '428.03', '6']]

文件应该是这样的:

value1  value2  value3  value4  LatX            LonY         HgtZ    sats        
1415    1417    119     337     47.06446389     15.45043694  428.08  6  
1436    1416    119     337     47.06446583     15.45044000  428.00  6  
1434    1418    119     318     47.06446583     15.45044333  428.03  6

我的代码(Python 3.7):

with open('your_file.txt', 'w') as f:
    for item in d:
        f.write("%s\n" % str(item))

此功能以d形式逐行打印列表


Tags: 文件代码列表yourwithopenitemvalue1
2条回答
with open('yourfile.txt', 'w') as f:
    for sublist in d:
        for s in sublist:
            f.write(str(s) + '\t')
        f.write('\n')

我用一些样本列表试过这个,效果很好。我只是打开文件,遍历列表列表并将元素按顺序排列

注意:正如许多伟大的用户在评论中所提供的那样,如果您以后不得不重新构建数据,这不是一个好方法。(可能有空格作为入口之一)

在阅读了这些很棒的建议后,我正在玩这些代码:

import csv
f = open('testfile.csv', 'w')

with f:
    writer = csv.writer(f)

    for row in d:
        writer.writerow(row)

从文件:

csvwriter.writerows(rows) Write all elements in rows (an iterable of row objects as described above) to the writer’s file object, formatted according to the current dialect.

参考: 1. Python docs

也许你可以用一些更像Python的东西,只是为了打印:

def printTable():
    headers = ['value1', 'value2', 'value3', 'value4', 'LatX', 'LonY', 'HgtZ', 'sats']
    table = [['431.84', '1417', '3.63', '10.28', '47.06446389', '15.45043694', '428.08', '6'],
             ['438.25', '1416', '3.63', '10.28', '47.06446583', '15.45044000', '428.00', '6'],
             ['437.64', '1418', '3.63', '9.7', '47.06446583', '15.45044333', '428.03', '6']]
    print ''.join(column.rjust(10) for column in headers)
    for row in table:
        print ''.join(str(column).rjust(10) for column in row)

如果要将数据写入文件,请使用上下文管理器with open('file.txt','w'),但请检查数据是否适合CSV,以便为新的运行读取数据:

import csv
headers = ['value1', 'value2', 'value3', 'value4', 'LatX', 'LonY', 'HgtZ', 'sats']
table = [['431.84', '1417', '3.63', '10.28', '47.06446389', '15.45043694', '428.08', '6'],
             ['438.25', '1416', '3.63', '10.28', '47.06446583', '15.45044000', '428.00', '6'],
             ['437.64', '1418', '3.63', '9.7', '47.06446583', '15.45044333', '428.03', '6']]
with open('test.csv', 'w', newline ='') as file:
   writer = csv.writer(file, delimiter=',')
   writer.writerow(i for i in headers)
   for j in table:
       writer.writerow(j)

相关问题 更多 >