George Tian
George Tian

Reputation: 441

How to rename files to include the filepath?

Right now, my exam files are ordered like so:

enter image description here

Where y stands for the year and s stands for the subject. Within each subject folder are 3 files - t1.txt, t2.txt and t3.txt, representing 3 different tests for that subject in that year.

I'm trying to group all the subjects together in one folder, and this requires adding the year to the beginning of the file name, other wise there will be 9 files with the same name.

My code so far is:

import os

mypath = 'D:\\Queensland Academies\\IB Resources\\test'

for root, subdir, file in os.walk(mypath):
    for f in file:
        new = 'test' + f
        print(new)
        os.rename(os.path.join(mypath, f), os.path.join(mypath, new))

However, this returns:FileNotFoundError: [WinError 2] The system cannot find the file specified

What am I doing wrong?

Edit: my current goal is not to move any files but to simply rename them

Upvotes: 2

Views: 69

Answers (1)

Patrick Artner
Patrick Artner

Reputation: 51633

import os

mypath = 'D:\\Queensland Academies\\IB Resources\\test'

for root, subdir, file in os.walk(mypath):
    for f in file:
        dirs = root.split("\\") [1:] # omit drive letter
        new = '_'.join(dirs) + '_' + f

        # print(new)
        os.rename(os.path.join(root, f), os.path.join(root, new))

gets the directory names from subdir omitting the drive letter and combines them with '_' and the original file name....

'mypath' is simply the starting path for os.walk() - it is not the location the file currently at hand is located at.


If I use this piece of code (replacing os.rename by print) I get for my C:\temp\:

c:\temp\a;b.txt           c:\temp\temp_a;b.txt
c:\temp\new 1.txt         c:\temp\temp_new 1.txt
c:\temp\new 2.txt         c:\temp\temp_new 2.txt
c:\temp\numbers.dat.txt   c:\temp\temp_numbers.dat.txt
c:\temp\tempfile.txt      c:\temp\temp_tempfile.txt
c:\temp\tempfile.txt.gz   c:\temp\temp_tempfile.txt.gz
c:\temp\tempfile.txt.gzip c:\temp\temp_tempfile.txt.gzip 

Upvotes: 1

Related Questions