[英]I want to use the directory name to use rather than the filename [on hold]
I want to use the name of the directory not the filename我想使用目录名而不是文件名
For example例如
path = os.path.basename("C:\folder1\folder2\device1\(I want this name of the file but i do not want to have to write it because it changes everytime i go into another directory) ")
I want to use the name of the directory after device1 but do not want to write it我想用device1后面的目录名但不想写
I have tried this我试过这个
path1 = os.path.basename(os.path.dirname(path))
this just comes back with an empty string path1 = os.path.basename(os.path.dirname(path))
这只是返回一个空字符串
You can do this你可以这样做
import os
path=os.path.dirname("C:/folder1/folder2/file.xml")
print(path) # Output:'C:/folder1/folder2'
print(os.path.basename(path)) # Output: 'folder2'
i think you should use pathlib
for this我认为你应该为此使用
pathlib
from pathlib import Path
path = Path(r'C:\folder1\folder2\device1\hello.csv')
path.parent.name # device1
path.name # hello.csv
pathlib
in my opinion is a bit more simple, and provides more functionality in paths and filesystem我认为
pathlib
更简单一些,并且在路径和文件系统中提供了更多功能
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.