为什么从os.walk()返回的根元素显示/作为目录分隔符,但os.sep(或os.path.sep)在Win10上显示\?] >
我只是试图为文件夹中的一组文件创建完整路径,如下所示:
import os base_folder = "c:/data/MA Maps" for root, dirs, files in os.walk(base_folder): for f in files: if f.endswith(".png") and f.find("_N") != -1: print(os.path.join(root, f)) print(os.path.sep)
这是我得到的输出:
可以与混合路径分隔符一起使用(至少在Windows上有效),但是依赖于这种hack确实不能在所有库中都得到信任。似乎从os.walk()和os.path(。sep或。join())返回的项目应基于< [操作系统正在使用。谁能解释为什么这种不一致的情况发生了?P.S。 -我知道在Python 3.4中引入了一个更统一的库,用于处理文件路径c:/data/MA Maps\Map_of_Massachusetts_Nantucket_County.png c:/data/MA Maps\Map_of_Massachusetts_Norfolk_County.png \
我知道python的某些库函数(像open())
((以及许多其他文件处理)]
,称为pathlib。如果您的代码在3.4或更高版本中使用,是否最好使用pathlib方法来解决此问题?但是,如果您的代码针对使用3.4之前的python的系统,那么解决此问题的最佳方法是什么?这是pathlib
的很好的基本解释:Python 3 Quick Tip: The easy way to deal with file paths on Windows, Mac and Linux这是我的代码和使用pathlib
:的结果:import os
from pathlib import Path
# All of this should work properly for any OS. I'm running Win10.
# You can even mix up the separators used (i.e."c:\data/MA Maps") and pathlib still
# returns the consistent result given below.
base_folder = "c:/data/MA Maps"
for root, dirs, files in os.walk(base_folder):
# This changes the root path provided to one using the current operating systems
# path separator (/ for Win10).
root_folder = Path(root)
for f in files:
if f.endswith(".png") and f.find("_N") != -1:
# The / operator, when used with a pathlib object, just concatenates the
# the path segments together using the current operating system path separator.
print(root_folder / f)
c:\data\MA Maps\Map_of_Massachusetts_Nantucket_County.png
c:\data\MA Maps\Map_of_Massachusetts_Norfolk_County.png
甚至可以仅使用和列表理解(使用所使用的每个操作系统正确处理所有路径分隔符)来更简洁地完成此操作:pathlib
from pathlib import Path
base_folder = "c:/data/MA Maps"
path = Path(base_folder)
files = [item for item in path.iterdir() if item.is_file() and
str(item).endswith(".png") and
(str(item).find("_N") != -1)]
for file in files:
print(file)
c:\data\MA Maps\Map_of_Massachusetts_Nantucket_County.png
c:\data\MA Maps\Map_of_Massachusetts_Norfolk_County.png
这是非常Python的语言,至少我觉得它很容易阅读和理解。 .iterdir()确实功能强大,并且可以以跨平台的方式相当轻松地处理文件和目录。您怎么看?
为什么从os.walk()返回的根元素显示/作为目录分隔符,但是os.sep(或os.path.sep)在Win10上显示\?我只是想在...
import os
from pathlib import Path
base_folder = Path("c:/data/MA Maps") # this will be normalized when converted to a string
for root, dirs, files in os.walk(base_folder):
for f in files:
if f.endswith(".png") and f.find("_N") != -1:
print(os.path.join(root, f))