0

I am trying to replace a '. ' with a '_' for all files in a directory. The files look like this:

000. utm_homescreen.bak
000. utm_homescreen.yxwz
001. utm_chain_screen.bak
001. utm_chain_screen.yxwz
...

Right now I am trying to apply a split and join to every file in the directory, but I don't see these changes reflected in the file names.

from pathlib import Path

for file in Path('..').glob('*'):
    if not file.is_dir():
        '_'.join(file.name.split('. '))
James D.
  • 165
  • 4
  • 14

3 Answers3

1

I ended up using Path.rename() like this:

for file in Path('..').glob('*'):
    if not file.is_dir():
        file.rename('_'.join(str(file).split('. ')))

Thanks for your responses.

James D.
  • 165
  • 4
  • 14
0

you forgot to use the rename function? i didn't runned but should look like this

changed like Mario Ishac suggested

from pathlib import Path

for file in Path('..').glob('*'):
    if not file.is_dir():
        Path(file.name).rename('_'.join(file.name.split('. ')))
L1v1u
  • 169
  • 3
0

Try using os.rename() and replace():

from os, glob
for file in glob.glob('*'): # list of all files in the folder
    if not file.is_dir():
        os.rename(file,file.replace('. ','_')) # rename the file with '. ' replaced with '_'
Red
  • 26,798
  • 7
  • 36
  • 58