-1

我用 Python 编写了一个比较 3 个 excel 文件的脚本。我有很多文件要使用此脚本,并且我希望它们以三个一组的形式使用。到目前为止,它大致是这样的:

#!/usr/bin/env python

import sys
import csv

#lots of functions

resultsdir = "."
#bla

filename1=sys.argv[1]
filename2=sys.argv[2]
filename3=sys.argv[3]
out = open(sys.argv[4],"w")

#filename1,filename2,filename3="CNVB_reads.403476","CNVB_reads.403447","CNVB_reads.403478"
#these are the 3 files it uses at the moment

file1=open(resultsdir+"/"+filename1+".csv")
file2=open(resultsdir+"/"+filename2+".csv") 
file3=open(resultsdir+"/"+filename3+".csv")

file1.readline()    
file2.readline()
file3.readline()

#lots of other irrelevant stuff
#the output goes into an excel file as well

一般来说,我是编程新手,我希望当我试图解释我想做的事情时我是有意义的。为任何帮助干杯!

4

1 回答 1

1

我会glob用来获取所有文件名,对它们进行排序,然后循环遍历它们(就像我在这里回答的那样)

# other imports
from glob import glob

# lots of functions

resultsdir = "."
counter = 0
outname = sys.argv[1]
files = sorted(glob(resultsdir+'/*.csv')) # get and sort .csv files
while len(files) >= 3: # Are there another 3 files?
    out = open(outname+'_'+str(counter)+'.csv',"w") # open an output file with an increasing number in name
    counter += 1 # increase output file number
    file1=open(files.pop(0)) # get and remove first file from the list
    file2=open(files.pop(0)) # get the next file from the list (is now the first)
    file3=open(files.pop(0))

    # do something with the files

    # close the files

第二种选择是使用(如评论中所述)使用

files = sorted(sys.argv[2:])

要获取文件,您必须像这样调用脚本:

program.py output_name *.csv

然后程序获取与通配符 ( *.csv) 匹配的所有文件的列表作为参数

于 2013-04-30T12:22:17.697 回答