Tuesday, October 16, 2018

Python Read List of Files from Text File in given Directory and Copy, Move to Another Directory with Error Handling


The reason for error handling is if the file exists in given text file multiple times, or maybe the file to copy given in the text file does not exist in source folder. This code was purposed for splitting protein fasta files to train and test fastas based on a given list. It can be used for other types of files. It is also possible to move the files from source directory by changing copy with move function.

Code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import shutil, os

source_path = 'combined_fastas/mouse/'
file_format = '.fasta'
files = []

with open('raw_data/mouse_train_proteins.txt', mode='r') as data:
    for line in data:
        files.append(line.rstrip())

#print(files)

for f in files:
    try:
        shutil.copy(source_path + f + file_format, 'split_fastas/mouse_train/')
    except:
        print('ERROR')
        continue

No comments: