我正在尝试读取特定目录下的所有文件的内容。我发现如果路径名不是以 /
结尾,那么我下面的代码将无法工作(将出现 I/O 异常,因为 pathName+f
不是有效 - 中间缺少 /
)。这是一个代码示例,显示它何时工作以及何时不工作,
我实际上可以使用endsWith检查pathName是否以/
结尾,只是想知道在连接路径和文件名作为全名时是否有更优雅的解决方案?
我的要求是,我想让输入路径名称更灵活,以 \
结尾,而不以 \
结尾。
使用Python 2.7。
from os import listdir
from os.path import isfile, join
#pathName = '/Users/foo/Downloads/test/' # working
pathName = '/Users/foo/Downloads/test' # not working, since not ends with/
onlyfiles = [f for f in listdir(pathName) if isfile(join(pathName, f))]
for f in onlyfiles:
with open(pathName+f, 'r') as content_file:
content = content_file.read()
print content
最佳答案
您只需再次使用 join 即可:
pathName = '/Users/foo/Downloads/test' # not working, since not ends with/
onlyfiles = [f for f in listdir(pathName) if isfile(join(pathName, f))]
for f in onlyfiles:
with open(join(pathName, f), 'r') as content_file:
content = content_file.read()
print content
或者您可以使用glob并忘记连接:
from glob import glob
pathName = '/Users/foo/Downloads/test' # not working, since not ends with/
onlyfiles = (f for f in glob(join(pathName,"*")) if isfile(f))
for f in onlyfiles:
with open(f, 'r') as content_file:
或者将其与过滤器结合以获得更简洁的解决方案:
onlyfiles = filter(isfile, glob(join(pathName,"*")))
关于python - 检查 Python 2.7 中文件目录路径是否有效的优雅方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38839902/