0

I'm trying to write only a file name to a .txt file, however, the entire file path is being written i.e. C:\Users\OneDrive\a.png

I only want a.png to be written. I know I can slice a string in python like this:

a="abcdefg"
print(a[2:4])
cd

but how do I do this at a fixed point in a string?

The file path will always remain static although the file name and length itself will change.

3
  • Firstly, it looks like you're using Python 2, though the cd doesn't even make sense in that context. If possible, use Python 3! Concerning string operations, just check out the documentation on the Python website to see if there's anything useful. Alternatively, run help(string) in an interactive session to retrieve some infos on the string type (unicode in version 3). Also, there are special path-handling methods to work with paths, which are better suited to this case. Commented Oct 3, 2021 at 20:14
  • Yeah, there's nothing on the string operation page of the documentation about splitting string unfortunately, I did take a look. And very much using p3. It's not a change directory cd if that's what you mean, it's the string index of a from the example. Commented Oct 3, 2021 at 20:20
  • Apologies, it's late here! Fixed the example. Commented Oct 3, 2021 at 20:24

1 Answer 1

1

you can split with \ and take the last element:

your_path = "C:\\Users\\OneDrive\\a.png"
print(your_path.split("\\")[-1])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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