1

I have files in a directory and the filenames are a substring of a list of strings. I need to rename the files with the strings in the list

filenames in "./temp" = aa.txt, bb.txt, cc.txt    
list_of_names = ['aa12.txt', 'bb12.txt', 'cc12.txt']

I want the files to be renamed to those in the list_of_names. Tried the code below but get an error

for filename in os.listdir('./temp'):
for i, item in enumerate(list_of_names):
    if filename in item:
        os.rename(filename,list_of_names[I])

FileNotFoundError: [Errno 2] No such file or directory: 'aa.txt' -> 'aa12.txt'

CDJB
  • 14,043
  • 5
  • 29
  • 55
robin_noob
  • 19
  • 1

3 Answers3

1

Try:

os.rename(‘./temp/‘ + filename, ‘./temp/‘+ list_of_names[i])

Also, consider using pathlib for file system operations.

CDJB
  • 14,043
  • 5
  • 29
  • 55
0

I think this would be simpler:

os.chdir('./temp')
for filename in os.listdir():
    for newname in list_of_names:
        if filename.split('.')[0] in newname.split('.')[0]:
            os.rename(filename, newname)

Note that 'aa.txt' in 'aa12.txt' is going to return False.

z242
  • 405
  • 4
  • 12
0
import os;
%loading names of files in A 
A = os.listdir();
%creating B for intermediate processing
B = os.listdir();
i = 0;
for x in A:
    t = x.split(".")    %temp variable to store two outputs of split string
    B[i] = t[0]+'12.txt'    
    os.rename(A[i],B[i])
    i = i+1
  • 1
    This answer contains several lines that are not valid python syntax. Lines do not end with ';', and comments do not start with '%'. Logic wise, there is no need to create the second list 'B' and populate it with the call to os.listdir()...you replace each element anyway. – z242 Nov 16 '19 at 21:31
  • This might not be the most efficient code. But this is definitely a working code. I have tried running it and got error free results for this. – Vamsi Dokku Nov 21 '19 at 09:39