【问题标题】:get the file path with Python on Windows error在 Windows 上使用 Python 获取文件路径错误
【发布时间】:2017-07-04 07:28:27
【问题描述】:

我想在我的 Windows 上用 Python 加载文件路径。 但现在有一个问题: 代码:

def Test2(rootDir):
    f = []
    for lists in os.listdir(rootDir): 
        path = os.path.join(rootDir, lists) 
        #print (path)
        #img = cv2.imread(path,0)
        #cv2.imshow("image",img)
        if os.path.isdir(path): 
            Test2(path)
        if os.path.isfile(path): 
            print (path)

Test2("D:/111test/picpic")

结果是:

D:/111test/picpic\haha1\111.png

结果不是我想要的,因为它包含'/'&'\'。 如何解决这个问题?

另一个问题: 我通过使用 Test2("D:\111test\picpic"); 成功获得了文件路径;

D:\111test\picpic\haha1\111.png

现在我想将这些文件路径替换成一个列表,我使用的代码:

if os.path.isfile(path): 
        print (path)
        f.append(path)
        print(f)

结果是我不想要的:

['D:\\111test\\picpic\\haha1\\111.png', 
 'D:\\111test\\picpic\\haha1\\222.png']

因为列表的文件路径包含双“\”。我该怎么办?

我的愿望:获取文件路径,并将它们正确放置在列表中。 我很喜欢你的方法!!!

很高兴您的回答!

【问题讨论】:

  • 将您的代码添加为文本而不是图片发布
  • 好的。已经完成了。请帮助我。
  • 那是因为您将目录分隔符指定为/,而它在您的操作系统(Windows)上是\。尝试调用类似Test2("D:\\111test\\picpic")的函数
  • @shahkalpesh 谢谢。这个问题已经解决了。但是现在我想把这些文件路径放在一个列表中。我使用这个代码:f.append(path) print(f) 结果是:['D:\\111test\\picpic\\haha1\\111.png', 'D:\\111test\\picpic\\haha1\\222.png'].如何解决?
  • ['D:\\111test\\picpic\\haha1\\111.png', 'D:\\111test\\picpic\\haha1\\222.png'] 有什么问题?请在原帖中详细说明额外的问题,并包括您希望获得的结果

标签: python filepath


【解决方案1】:

在处理 Windows 路径时,您应该改用 pathlib。如果您使用的是 Python 2,也可以使用 package

举个例子,如何使用 pathlib 库:

def Test2(rootDir):
    f = []
    rootDir = pathlib.Path(rootDir)
    for iter_file in rootDir.iterdir(): 
        if iter_file.is_dir(): 
            Test2(iter_file)
        if iter_file.is_file(): 
            print(iter_file)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-01
    • 2012-07-10
    • 2017-09-09
    • 2021-09-10
    • 2018-05-26
    • 2017-07-07
    相关资源
    最近更新 更多