简体   繁体   English

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

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

I am trying to read content of all files under a specific directory. 我正在尝试读取特定目录下所有文件的内容。 I find it is a bit tricky if path name is not ends with / , then my code below will not work (will have I/O exception since pathName+f is not valid -- missing / in the middle). 我发现如果路径名不是以/结尾的话会有些棘手,那么下面的代码将不起作用(由于pathName+f无效-中间缺少/ ,因此将出现I / O异常)。 Here is a code example to show when it works and when it not works, 这是一个代码示例,展示了它什么时候起作用,什么时候不起作用,

I can actually check if pathName ends with / by using endsWith, just wondering if more elegant solutions when concatenate path and file name for a full name? 我实际上可以通过使用endsWith检查pathName是否以/结尾,只是想知道在将路径和文件名连接为全名时是否有更优雅的解决方案?

My requirement is, I want to give input pathName more flexible to ends with both \\ and not ends with \\ . 我的要求是,我想给输入pathName更灵活的名称,使其既以\\结尾,也不以\\结尾。

Using Python 2.7. 使用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

You would just use join again: 您只需要再次使用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

Or you could use glob and forget join: 或者您可以使用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:

or combine it with filter for a more succinct solution: 或将其与过滤器结合使用,以获得更简洁的解决方案:

onlyfiles = filter(isfile, glob(join(pathName,"*")))

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

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