robin_noob
robin_noob

Reputation: 19

Rename file with parent string if filename is a substring of list of strings

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'

Upvotes: 1

Views: 530

Answers (3)

Vamsi Dokku
Vamsi Dokku

Reputation: 1

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

Upvotes: 0

z242
z242

Reputation: 435

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.

Upvotes: 0

CDJB
CDJB

Reputation: 14546

Try:

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

Also, consider using pathlib for file system operations.

Upvotes: 1

Related Questions