微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在许多文件上运行python脚本来获取许多输出文件?

我是编程新手,我写了一个脚本从vcf文件提取文本。 我正在使用Linux虚拟机并运行Ubuntu。 我已经通过命令行运行这个脚本,把我的目录改成带有vcf文件文件,然后inputpython script.py 。

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

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

该脚本将我需要的信息放入列表中,然后将其写入输出文件。 但是,我有许多input文件(都是.vcf ),并且希望将它们写入到与input类似的不同输出文件(如input_processed.txt )。

我是否需要运行一个shell脚本来迭代文件夹中的文件? 如果是的话,我将如何改变python脚本来适应这个? 即将列表写入输出文件

这个shell命令是什么意思是“exec 3>&1>>(logger -t”OKOK“)”

通过可靠的方式调用远程bashfunction

小sh脚本logging进程内存和cpu使用率

如何使用awk将文件的某个字段更改为大写?

一个文件中find一行,并在bash中添加一些内容到行尾

更改脚本的root密码

redirect之后的一个参数能做什么吗?

使用variables名创build一个数组bash,unix

Powershell文件夹大小sorting与自动大小转换

启动nano编辑器通过pipe道命令

我将它整合到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 ...

你不需要写shell脚本,也许这个问题会帮助你?

如何列出目录的所有文件

这取决于你如何实现迭代逻辑。

如果你想在python中实现它,只要做到这一点;

如果您想在shell脚本中实现它,只需将您的python脚本更改为接受参数,然后使用shell脚本使用适当的参数调用python脚本。

我有一个我经常使用的脚本,其中包括使用PyQt5弹出一个窗口,提示用户选择一个文件…然后它走过目录查找目录中的所有文件

pathname = first_fname[:(first_fname.rfind('/') + 1)] #figures out the pathname by finding the last '/' new_pathname = pathname + 'for release/' #makes a new pathname to be added to the names of new files so that they're put in another directory...but their names will be altered file_list = [f for f in os.listdir(pathname) if f.lower().endswith('.xls') and not 'map' in f.lower() and not 'check' in f.lower()] #makes a list of the files in the directory that end in .xls and don't have key words in the names that would indicate they're not the kind of file I want

您需要导入os才能使用os.listdir命令。

你可以使用listdir( 你需要编写条件来过滤特定的扩展名 )或glob。 我通常更喜欢glob。 例如

import os import glob for file in glob.glob('*.py'): data = open(file,'r+') output_name = os.path.splitext(file)[0] output = open(output_name+'.txt','w') output.write(data.read())

代码将从输入中读取内容并将其存储在outputfile中。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐