python - 将多个列表写入多个输出文件

标签 python list io

我正在处理存储在大型文本文件中的数据集。对于我正在执行的分析,我打开文件,提取部分数据集并比较提取的子集。我的代码的工作原理如下:

from math import ceil

with open("seqs.txt","rb") as f:
    f = f.readlines()

assert type(f) == list, "ERROR: file object not converted to list"

fives = int( ceil(0.05*len(f)) ) 
thirds = int( ceil(len(f)/3) )

## top/bottom 5% of dataset
low_5=f[0:fives]
top_5=f[-fives:]

## top/bottom 1/3 of dataset
low_33=f[0:thirds]
top_33=f[-thirds:]

## Write lists to file
# top-5
with open("high-5.out","w") as outfile1:
   for i in top_5:
       outfile1.write("%s" %i)
# low-5
with open("low-5.out","w") as outfile2:
    for i in low_5:
        outfile2.write("%s" %i)
# top-33
with open("high-33.out","w") as outfile3:
    for i in top_33:
        outfile3.write("%s" %i)
# low-33        
with open("low-33.out","w") as outfile4:
    for i in low_33:
        outfile4.write("%s" %i)

我正在尝试找到一种更聪明的方法来自动化将列表写入文件的过程。在本例中只有 4 个,但在将来我可能会得到多达 15-25 个列表时,我会使用一些函数来处理这个问题。我写了以下内容:

def write_to_file(*args):
    for i in args:
        with open(".out", "w") as outfile:
            outfile.write("%s" %i)

但是当我像这样调用函数时,结果文件仅包含最终列表:

write_to_file(low_33,low_5,top_33,top_5)

我知道我必须为每个列表定义一个输出文件(我在上面的函数中没有这样做),我只是不确定如何实现它。有任何想法吗?

最佳答案

使变量名与文件名匹配,然后使用字典来保存它们,而不是将它们保存在全局命名空间中:

data = {'high_5': # data
       ,'low_5': # data
       ,'high_33': # data
       ,'low_33': # data}

for key in data:
    with open('{}.out'.format(key), 'w') as output:
        for i in data[key]:
            output.write(i)

将您的数据保存在一个易于使用的位置,假设您想对它们应用相同的操作,您可以继续使用相同的范例。

正如下面 PM2Ring 所提到的,建议使用下划线(如在变量名中所做的那样)而不是破折号(如在文件名中所做的那样),因为这样做可以将字典键作为关键字参数传递到书写功能:

write_to_file(**data)

这相当于:

write_to_file(low_5=f[:fives], high_5=f[-fives:],...) # and the rest of the data

从中您可以使用其他答案定义的函数之一。

关于python - 将多个列表写入多个输出文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30506809/

相关文章:

python - 开发可在不同环境中运行的Python软件

python - 如何避免使用 Python 多处理在 fork 进程中加载​​父模块

Python - 从字典列表中提取值(由 SQL 命令生成)

python - 对列表元素进行 Grep

python - python - 不使用random.shuffle()随机化元组列表

c - 你如何在 C 中的 Linux 上进行非阻塞控制台 I/O?

c++ - 与阅读不同格式的数字字符有关的问题

Python正则表达式错误: "Can' t assign to operator"

python - 减去两个包含 datetime.time 的 numpy 数组

c# - 使用 File.Copy 时如何实现超时?