python - 检查 Python 2.7 中文件目录路径是否有效的优雅方法

标签 python python-2.7

我正在尝试读取特定目录下的所有文件的内容。我发现如果路径名不是以 / 结尾,那么我下面的代码将无法工作(将出现 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/

相关文章:

python - 为什么线程分布在 CPU 之间?

python - 来自发布原始数据的django ImageField

初始化字典的 Python KeyError 异常

python - 用于捕获和替换字符串中除特殊模式外的所有数字的 RegEx

python - 清理模板代码

java - 什么是\xHEX 字符?是否有它们的表格?

python - 如何使用 conda 创建单独的 python 环境,每个环境都有不同的 $PYTHONPATH

python - python中main函数调用失败

python - JSON 类型错误 : expected string or buffer

python - 从 Python Pandas/Dask 中的 Parquet 文件读取一组行?