Neil
Neil

Reputation: 3281

How to edit the filename of a path string

I have a list of file paths eg:

file_paths = [
    'repo/batcha/somefile.txt',
    'repo/batcha/someotherfile.txt',
]

I want to loop over then and add an id to each filename.

for _id, path in enumerate(file_paths):
    <add _id to filename>

With an expected output something like:

[
    'repo/batcha/node1_somefile.txt',
    'repo/batcha/node2_someotherfile.txt',
]

I can of course use filename.split('/') on these examples to get at the filename part. I would like to know whether there is, however, a solution using something like os.path that could consistently extract the filename portion of a path in an os independent manner.

Upvotes: 0

Views: 44

Answers (1)

Sushanta Das
Sushanta Das

Reputation: 131

To keep your code OS independent, you can use os.sep which is '\' in windows and '/' in linux/unix systems. Below is just an example how can you break and reconstruct paths again.

for _id, path in enumerate(file_paths):
    leafs = path.split('/')
    new_path = os.sep.join(leafs)
    print(new_path)

Upvotes: 2

Related Questions