python - 如何在多个文件上运行 python 脚本以获得多个输出文件?

标签 python linux bash shell python-2.7

我是编程新手,我编写了一个脚本来从 vcf 文件中提取文本。我正在使用 Linux 虚拟机并运行 Ubuntu。我通过命令行运行此脚本,方法是将我的目录更改为包含 vcf 文件的文件,然后输入 python script.py

我的脚本知道要处理哪个文件,因为我的脚本开头是:

my_file = open("inputfile1.vcf", "r+")
outputfile = open("outputfile.txt", "w")

脚本将我需要的信息放入一个列表中,然后我将其写入输出文件。但是,我有很多输入文件(都是 .vcf),想将它们写入与输入名称相似的不同输出文件(例如 input_processed.txt)。

我是否需要运行 shell 脚本来遍历文件夹中的文件?如果是这样,我将如何更改 python 脚本以适应这个?即将列表写入输出文件?

最佳答案

我会将它集成到 Python 脚本中,这样您也可以轻松地在其他平台上运行它,并且不会添加太多代码。

import glob
import os

# Find all files ending in 'vcf'
for vcf_filename in glob.glob('*.vcf'):
    vcf_file = open(vcf_filename, 'r+')

    # Similar name with a different extension
    output_filename = os.path.splitext(vcf_filename)[0] + '.txt'
    outputfile = open(output_filename, 'w')

    # Process the data
    ...

要将生成的文件输出到单独的目录中,我会:

import glob
import os

output_dir = 'processed'
os.makedirs(output_dir, exist_ok=True)

# Find all files ending in 'vcf'
for vcf_filename in glob.glob('*.vcf'):
    vcf_file = open(vcf_filename, 'r+')

    # Similar name with a different extension
    output_filename = os.path.splitext(vcf_filename)[0] + '.txt'
    outputfile = open(os.path.join(output_dir, output_filename), 'w')

    # Process the data
    ...

关于python - 如何在多个文件上运行 python 脚本以获得多个输出文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34038764/

相关文章:

python - django:django.core.exceptions.AppRegistryNotReady:应用程序尚未加载

python - 为什么在目录中循环访问.wav文件时显示错误,但在不循环时工作正常?

linux - 对文本文件中的每个 id 运行命令

linux - Bash:将字符串中的特定模式设为小写

python - Discord.py - 如何检测用户是否提及/ping 机器人

在timeval和clock()之间选择来计算C中的耗时

c++ - 非系统 g++ 链接系统库,忽略 rpath

linux - kill -9 $pid 的返回值

linux - 如何查找特定文件

python - 从 python 程序中禁用哈希随机化