首页 > 解决方案 > 如何使用列表打印未知数量的字典键来识别键?

问题描述

所以我搜索并找到了一些帮助我将这段代码放在一起的东西,但我对最后一部分没有任何运气。我想要做的是读取逗号分隔、空格分隔或制表符分隔的文件,将标题设置为键,将数据设置为值,然后仅将某些列(列数未知)写入输出文件。Example.txt 如下所示:

col1, col2, col3, col4, col5
1, 11, 21, 31, 41
2, 12, 22, 32, 42
3, 13, 23, 33, 43
4, 14, 24, 34, 44

到目前为止,这是我到目前为止的工作代码。

import csv
import sys

file = sys.argv[1] # name of file is example.txt
columns = sys.argv[2:] # order: col1, col3, col5

with open(file, 'r') as csvfile:
    with open('table.out', 'w') as file_out:
        file.out_write(columns[0] + '\t' + columns[1] + '\t' + columns[2] + '\n')

        reader = csv.DictReader(csvfile)
        for row in reader:
            file_out.write(row[columns[0]] + '\t' + row[columns[1]] + '\t' + row[columns[2]] + '\n') 

结果:

col_1    col_3    col_5
1    21    41
2    22    42
3    23    43
4    24    44

如果列数是固定数字,则此代码效果很好,但要写入的列数可能会有所不同。例如,有时我可能只想抓取 col1、col2,而其他时候我可能想不按特定顺序抓取 col2、col3、col4、col5。

所以我的问题是,如何修改上面的代码,以便可以使用 Python 3.X 中的字典将任意数量的列写入输出文件?

标签: pythonpython-3.xdictionary

解决方案


您可以根据自己的需要进行调整,但基本上使用该join功能将非常有帮助 + 列表理解。

import csv
import sys

file = sys.argv[1]
columns = sys.argv[2:]

with open(file) as f:
    myread = csv.DictReader(f)
    for row in myread:
        print('\t'.join([row[i] for i in columns]))

推荐阅读