0

New learner. I have several txt files in a folder. I need to change the 'April' into 'APR'.

12 April 2019 Nmae's something Something.txt

13 April 2019 World's - as Countr something.txt

14 April 2019 Name and location.txt

15 APR 2019 Name then location,for something.txt

So it looks like this

12 APR 2019 Nmae's something Something.txt

13 APR 2019 World's - as Countr something.txt

14 APR 2019 Name and location.txt

15 APR 2019 Name then location,for something.txt

Here are links with the similar ones, but each of them are slightly different.

Python - Replace multiple characters in one file name

CHange multiple file name python

PYTHON - How to change one character in many file names within a directory

How to change multiple filenames in a directory using Python

I tried this:

import os
files = os.listdir('/home/runner/Final/foldername')
   for f in files:
newname = f.replace('April', 'APR')
os.rename(f, newname)

But nothing changed, can I get some guide?

Maibaozi
  • 47
  • 8
  • 1
    This might be due to your working directory. When you call `os.rename(f, ...)` it needs to know where `f` is. Giving a full path via `os.path.join('/home/runner/Final/foldername', f)` might help. I'm not sure if you then need to also use `os.path.join('/home/runner/Final/foldername', newname)` as well. – Kraigolas Jan 06 '22 at 00:25

1 Answers1

2

The problem is that f is just the filename, not the full path, so your command os.rename(f, newname) would rename a file named f in the current working directory, not the target directory. Also, you'd attempt to rename every file instead of just the ones that actually change.

Here's something a bit better:

from pathlib import Path


for f in Path('/home/runner/Final/foldername').glob('*'):
    if f.is_file():
        new_name = f.name.replace('April', 'APR')
        if new_name != f.name:
            f.rename(Path('/home/runner/Final/foldername') / new_name)

It also checks if something that was found is actually a file (otherwise, it would include directories, and it appears you don't want to rename those).

Note that, in the most recent version of Python, this also works:

for f in Path('/home/runner/Final/foldername').glob('*'):
    if f.is_file():
        if (new_name := f.name.replace('April', 'APR')) != f.name:
            f.rename(Path('/home/runner/Final/foldername') / new_name)

And to avoid continually reconstructing a Path object:

folder = Path('/home/runner/Final/foldername')

for f in folder .glob('*'):
    if f.is_file():
        if (new_name := f.name.replace('April', 'APR')) != f.name:
            f.rename(folder / new_name)
Grismar
  • 27,561
  • 4
  • 31
  • 54