1

Beginer python coder here.

I've been struggling with this problem for few days now and finally given up and seeking help.

Problem illustrated:

All Student folders:
Student a: 
    Work.pdf
    Work2.pdf
Student b:
    Work.pdf
    Work2.pdf 

Folders Student a and student b, contain two files each. I need to rename those files as homework1.pdf and homework2.pdf

Ofcourse in real life I have more than 2 folders. I thought a for loop using os.rename() would work but I can't get it to change multiple files.

Here's what I tried

import os

# assign directory
directory = 'all Student folders'

# iterate over files 

for root, dirs, files in os.walk(directory):
  for filename in files:
    if filename =='work.pdf':
      os.rename('work.pdf', homework1.pdf')
 

Many thanks...

Floh
  • 745
  • 3
  • 16
Ghost786
  • 13
  • 3

1 Answers1

0

You need to use the file in the dir where it is.

import os

# assign directory
directory = "all Student folders"

# iterate over files

for root, _, files in os.walk(directory):
    for file_name in files:
        if file_name == "Work.pdf":
            os.rename(f"{root}/{file_name}", f"{root}/homework1.pdf")
        else:
            new_name = file_name.replace(f"Work", "homework")
            os.rename(f"{root}/{file_name}", f"{root}/{new_name}")
Floh
  • 745
  • 3
  • 16
  • 1
    Thank you so much Fioh! It worked! Now I can manipulate it and use when I need. If you have some time I'd really appreciate if you could explain the script for us newbies. Or direct me to where I can learn more.. – Ghost786 Apr 13 '22 at 20:03
  • f"" is named f-string and allows to template a string – Floh Apr 13 '22 at 20:12
  • os.walk retrive for each root the folders and files it contains. We don't use folders so put underscore as variable name. When we move a file, the filename is not enough, you need to specify its location (root). – Floh Apr 13 '22 at 20:13
  • 1
    Thank you for the explanation, that makes sense I couldn't move into the different folders as I was just using file name. Brilliant! – Ghost786 Apr 13 '22 at 20:49