Python script to get file path from folder to text file
import shutil
import os
def get_files():
source = os.listdir("/output_folder/sample/cufflinks/")
destination = "output_folder/assemblies.txt"
for files in source:
if files.with("transcripts.gtf"):
shutil.move(files,destination)
I want to get transcripts.gtf
files from "/output_folder/sample/cufflinks/"
to assemblies.txt
. Whether the above code is correct or not. Please help me. Thank!
+3
source to share
2 answers
You can use os.walk :
import os
import shutil
from os.path import join
destination = "/output_folder/assemblies.txt" # Absolute path, or use join
folder_to_look_in = "/output_folder/sample/cufflinks/" # Absolute folder path, or use join
for _, _, files in os.walk(folder_to_look_in):
for file_name in files:
if file_name.endswith("transcripts.gtf"):
try:
# 'a' will append the data to the tail of the file
with open(destination, 'a') as my_super_file:
my_super_file.write(file_name)
except OSError as e:
print "I/O error({0}): {1}".format(e.errno, e.strerror)
+2
source to share
I think I finally understand what you are trying to achieve. Use glob.glob () function :
import glob
destination = "output_folder/assemblies.txt"
source = '/output_folder/sample/cufflinks/*/*transcripts.gtf'
with open(destination, 'w') as f:
f.write('\n'.join(glob.glob(source))+'\n')
f.write('\n'.join(glob.glob(source))+'\n')
is equivalent to:
s = ''
for path in glob.glob(source):
s += '{}\n'.format(path)
f.write(s)
+2
source to share