-1

I have a list of files for which I would like to replace a substring within their name. The glob.glob(path) returns:

'./path\\2016_Joe_Black_tall_blond',
etc.

where Joe_Black should become Joe-Black. I would have to do the same for other names, e.g. Tim_Blue becomes Tim-Blue etc. (can I gather all those into names=[Joe_Black, Tim_Blue ...] ?)

I have found multiple approaches online, but what would be the best to do it?

Andreuccio
  • 1,053
  • 2
  • 18
  • 32

1 Answers1

0

You can use list comprehension for this purpose. In this example, I simply replace _ by -. Note basename is used to extract the name of the file and not its full path.

import glob
import os

path = "./data/"
# Make list of paths
names = glob.glob(os.path.join(path, "*")) 
# Returning a list of file names (without path) where a character is replaced
names = [os.path.basename(name).replace('_', '-') for name in names]
Romain
  • 19,910
  • 6
  • 56
  • 65