简体   繁体   中英

How to modify a path which's in a variable (python)?

After finding the path of the Python file which I am actually working on with os.getcwd() and __file__ I want to modify it, so if I put it in a variable named r and then delete one part of the path that will be very good. For example, the path is 'C:\\\\Users\\\\Shadow\\\\Desktop\\\\213.py' if I want to delete \\\\213.py from the path ( r ) how can I do that?

you can manipulate your string:

r = 'C:\\Users\\Shadow\\Desktop\\213.py'
r.rsplit('\\', 1)[0]

output:

'C:\\Users\\Shadow\\Desktop'

you may also want to have a look over pathlib.Path

You extract the directory name in your example. This is easily achieved with os.path.dirname .

import os
os.path.dirname(__file__)

This solution is cross-platform (mostly), and avoids most pitfalls that arise from treating paths as strings.

If you need the value stored in a variable:

import os
r = on.path.dirname(__file__)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM