Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从python中的文件路径获取文件名_Python_Variables - Fatal编程技术网

从python中的文件路径获取文件名

从python中的文件路径获取文件名,python,variables,Python,Variables,这个问题已经有了一个解决方案,但在我的情况下,我没有得到正确的解决方案,我哪里做错了 import os,sys filename = "C:\Users\Dell\Desktop\ProjectShadow\app2\aapp2s.py" directory, module_name = os.path.split(filename) module_name = os.path.splitext(module_name)[0] print(module_name) print(director

这个问题已经有了一个解决方案,但在我的情况下,我没有得到正确的解决方案,我哪里做错了

import os,sys
filename = "C:\Users\Dell\Desktop\ProjectShadow\app2\aapp2s.py"
directory, module_name = os.path.split(filename)
module_name = os.path.splitext(module_name)[0]
print(module_name)
print(directory)

我想要什么

>> 
aapp2s
C:\User\Dell\Desktop
有什么问题吗?

可以使用
r“C:\Users\Dell\Desktop\ProjectShadow\app2\aapp2s.py”
或者您可以将整个过程反斜切两次
“C:\\Users\\Dell\\Desktop\\ProjectShadow\\app2\\aapp2s.py”


您在打印上看到的奇怪现象是\a转义字符的结果

Try
pathlib

from pathlib import PureWindowsPath
filename = r"C:\Users\Dell\Desktop\ProjectShadow\app2\aapp2s.py"
p = PureWindowsPath(filename)
module_name = p.stem
directory = p.parents[2]
print(module_name)
print(directory)
输出:


您缺少原始前缀
r“C:\users\…
\a
是一个特殊的转义序列。应转义字符串文本中的反斜杠。例如
“C:\\users\\Dell\\Desktop\\ProjectShadow\\app2\\aapp2s.py”
,或使用
r
前缀,例如
r“C:\users\Dell\Desktop\ProjectShadow\app2\aapp2s.py”“
如果链接存储在变量中怎么办?如何使用正则表达式r'?对于变量???@amitnair92,您可以使用类似于
newText=“%r”%textFromVariable
aapp2s
C:\Users\Dell\Desktop