繁体   English   中英

检查文件目录路径在Python 2.7中有效的一种优雅方法

[英]elegant way to check file directory path valid in Python 2.7

我正在尝试读取特定目录下所有文件的内容。 我发现如果路径名不是以/结尾的话会有些棘手,那么下面的代码将不起作用(由于pathName+f无效-中间缺少/ ,因此将出现I / O异常)。 这是一个代码示例,展示了它什么时候起作用,什么时候不起作用,

我实际上可以通过使用endsWith检查pathName是否以/结尾,只是想知道在将路径和文件名连接为全名时是否有更优雅的解决方案?

我的要求是,我想给输入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,"*")))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM