I am running the following code :
foldarz = [ f.path for f in os.scandir('.') if f.is_dir() ]
print(foldarz)
This prints the folder name correctly, but with a prepended ".\\". I don't want the ".\\".
I know I can split the string etc, but I assume there's a better way without having to call another function.
你可以这样做os.path.basename
:
foldarz = [os.path.basename(f) for f in os.scandir('.') if f.is_dir()]
os.path.normpath
应该可以帮助您删除前导 '.\\' 并为您提供操作系统首选的规范化路径(根据用户的操作系统考虑使用 '/' 而不是 '\\')
foldarz = [os.path.normpath(f) for f in os.scandir('.') if f.is_dir()]
If you don't want to use other functions, you can also use os.DirEntry.name
:
foldarz = [ f.name for f in os.scandir('.') if f.is_dir() ]
print(foldarz)
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.