python读取>分析>打印多个文件

2024-05-01 22:09:51 发布

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

我有6个类似格式但不同名称的文件。 (例如,文件_AA.dat公司文件_起始日期文件_交流数据文件_营业执照文件_BB.dat公司文件_BC.dat公司)在

我是否可以编写一个for循环脚本来一次读取、分析和打印这些文件,而不是操作脚本6次?例如

for i in {AA AB AC BA BB BC} 
 filename = 'file_$i.dat'
 file = open (filename, 'r')
 Do a lot, lot of analysis for lots of rows and columns :P 
 file open('output_file_$i.dat','w')
 Do some for loop for writing and calculation 
file.close

因此,我希望能够同时自动化读取/分析/写入不同文件(但格式相似)的过程。我很好奇如何处理它的输入/输出部分的命名。通过这种方式,我希望能够更快速、更容易地分析大量的文件。在

或者,有没有什么方法可以使用python和Cshell或shell脚本的混合来实现这一点呢?在

谢谢你


Tags: 文件of脚本for格式公司openfilename
3条回答

您可以使用列表理解来清晰地执行此操作:

for filein, fileout in [('file_%s.dat' % x, 'out_%s.dat' %x) for x in ('AA','AB','AC', 'BA', 'BB', 'BC')]:
    with open(filein, 'rb') as fp, open(fileout,'w') as fpout:
        # Read from fp, write to fpout as needed

此列表理解创建输入/输出文件对的列表:

^{pr2}$

这将生成一个如下所示的列表:

[('file_AA.dat', 'out_AA.dat'), ('file_AB.dat', 'out_AB.dat') ...]

您可以尝试这样测试它的工作方式:

lst = [('file_%s.dat' % x, 'out_%s.dat' %x) for x in ('AA','AB','AC', 'BA', 'BB', 'BC')]:
print lst

for filein, fileout in lst:
    with open(filein, 'rb') as fp, open(fileout,'w') as fpout:
        # Read from fp, write to fpout as needed
files = [
    "file_AA.dat",
    "file_AB.dat",
    "file_AC.dat",
    "file_BA.dat",
    "file_BB.dat",
    "file_BC.dat",
]
for filename in files:
    f = open(filename)
    data = f.read() #reads all data from file into a string
    #parse data here and do other stuff
    output = open("output_"+filename, 'w')
    output.write(junk) #junk is a string that you shove the results into
    output.close()

如果您有大量的文件,并且您正在对文件中的数据进行大量计算分析,那么可以使用multiprocessing模块。至于bash vs python,我基本上使用python解释器,就像很多人使用bashshell一样,我几乎没有理由离开python解释器。另外,如果这些文件是目录中唯一的文件,则可以使用os模块遍历目录。如果必须在bashshell中运行程序,可以使用subprocess模块。在

其思想是迭代文件名,循环打开每个文件,进行分析,然后写入输出文件:

filenames = ['file_AA.dat', 'file_AB.dat', 'file_AC.dat', 'file_BA.dat', 'file_BB.dat', 'file_BC.dat']

for filename in filenames:
    with open(filename, 'r') as input_file:
        # Do a lot, lot of analysis for lots of rows and columns :P

    with open('output_%s' % filename, 'w') as output_file:
        # Do some for loop for writing and calculation

请注意,在处理文件时建议使用with statement。在

另请注意,您可以将这两个语句合并为一个语句,请参见:

UPD:可以使用string formatting来构造文件名列表:

^{pr2}$

希望有帮助。在

相关问题 更多 >