简体   繁体   English

如何修改变量(python)中的路径?

[英]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.在找到我实际使用os.getcwd()__file__处理的 Python 文件的路径后,我想修改它,所以如果我把它放在一个名为r的变量中,然后删除路径的一部分,那将非常好的。 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?例如,路径是'C:\\\\Users\\\\Shadow\\\\Desktop\\\\213.py'如果我想从路径 ( r ) 中删除\\\\213.py我该怎么做?

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你可能还想看看pathlib.Path

You extract the directory name in your example.您在示例中提取目录名称。 This is easily achieved with os.path.dirname .这可以通过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__)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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