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.

asked Apr 6, 2020 at 14:15
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)
answered Apr 6, 2020 at 14:30
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.