0

I have to change the name of several files in a folder such as:

CO201_LF.ab1
CO202_LF.ab1
CO034_LF.ab1
CO9871_LF.ab1
CO9576_LF.ab1

And replace those names with the names that I have in a list in a txt file.

How I can do that?

For the moment I have tried this without good results:

import os, fnmatch

def change_name():
    
    file_path = '/home/SCRIPT_BIO/thesis_CSU/rbcL_LF_consolidated/ab1_RAW/'>
    
    files_to_rename = fnmatch.filter(os.listdir(file_path), '*.ab1')
        
    print(files_to_rename)
    
    new_name = '/home/SCRIPT_BIO/thesis_CSU/rbcL_LF_consolidated/ab1_RAW/spp_list.txt/'>
        
    for i, file_name in enumerate(files_to_rename):
        new_file_name = new_name + str(i) + '.ab1'
    
        os.rename(file_path + file_name,
              file_path + new_file_name)
    
if __name__ == '__main__':
    change_name()

The message that I have gotten is this:

"FileNotFoundError: [Errno 2] No such file or directory: '/home/SCRIPT_BIO/thesis_CSU/rbcL_LF_consolidated/ab1_RAW/CO201_LF.ab1' -> '/home/SCRIPT_BIO/thesis_CSU/rbcL_LF_consolidated/ab1_RAW//home/SCRIPT_BIO/thesis_CSU/rbcL_LF_consolidated/ab1_RAW/spp_list.txt0'"

What I want to get or the final product that I expect to get are those files (CO201_LF.ab1, etc.) renamed by the names in that list (spp_list.txt) in the same order.

Aegiphylla monica.ab1
Eugenia edulis.ab1
Miconia sparata.ab1
Deutemia claricia.ab1
Drapteris lineata,ab1

Maybe someone can help me?

1 Answers1

0

Indent the os.rename() to be part of the "for" loop.

def change_name():

    file_path = '/home/SCRIPT_BIO/thesis_CSU/rbcL_LF_consolidated/ab1_RAW/'>

    files_to_rename = fnmatch.filter(os.listdir(file_path), '*.ab1')
    
    print(files_to_rename)

    new_name = '/home/SCRIPT_BIO/thesis_CSU/rbcL_LF_consolidated/ab1_RAW/spp_list.txt/'>
    
    for i, file_name in enumerate(files_to_rename):
        new_file_name = new_name + str(i) + '.ab1'

        os.rename(file_path + file_name,
              file_path + new_file_name)

if __name__ == '__main__':
     change_name()
  • done, but the the message is the same – shawn_smith_kaviedes Aug 12 '22 at 20:23
  • The file name looks like a malformed concatenation of two different file names:'/home/SCRIPT_BIO/thesis_CSU/rbcL_LF_consolidated/ab1_RAW//home/SCRIPT_BIO/thesis_CSU/rbcL_LF_consolidated/ab1_RAW/spp_list.txt0' –  Aug 18 '22 at 16:53