0

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.

2
  • 1
    What about this answer? Otherwise, maybe this regular expression? Commented Apr 6, 2020 at 14:30
  • pathlib is a good recommendation Commented Apr 6, 2020 at 14:41

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.