2015-12-02 35 views
1

我是編程新手,我寫了一個腳本從vcf文件中提取文本。我正在使用Linux虛擬機並運行Ubuntu。我已通過命令行運行此腳本,方法是將我的目錄更改爲vcf文件所在的文件,然後輸入python script.py如何在許多文件上運行python腳本來獲取許多輸出文件?

我的腳本知道要處理的文件,因爲我的劇本的開頭是:

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

腳本會將我需要的信息到一個列表,然後我把它寫來OUTPUTFILE。但是,我有很多輸入文件(全部爲.vcf),並且希望將它們寫入與輸入名稱類似的不同輸出文件(如input_processed.txt)。

我是否需要運行shell腳本來迭代文件夾中的文件?如果是的話,我將如何改變python腳本以適應此? I.e將列表寫入輸出文件?

+0

迭代輸入文件名 – Zety

回答

1

我會將它集成到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 
    ... 
+0

嗨!這工作完美!儘管原始文件是數字和文本,所以我使用「_」作爲分隔符,然後將「_processed」添加到最後。我現在唯一想知道的其他事情是如何將它們全部添加到我所在目錄中的文件夾?如在,將所有文件添加到一個新建立的文件夾稱爲「已處理」? – trouselife

+0

我已經更新了答案,以顯示如何爲排序腳本執行此操作。 – Takis

0

這取決於你如何實現迭代邏輯。

  1. 如果你想在Python中實現它,只需要它;

  2. 如果要在shell腳本中實現它,只需將您的python腳本更改爲接受參數,然後使用shell腳本使用適當的參數調用python腳本。

0

我有一個劇本,我經常用這包括使用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命令。

0

您可以使用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中。

相關問題