首页 > 解决方案 > python os path join 似乎在 win 和 OSX OS 之间无法正常工作

问题描述

我遇到了一段在 OSX 和 Windows 上运行的简单代码的问题。我正在使用 Python 3.7.9。

我所做的只是将路径链接到文件名;我读取了一个目录内容,然后创建了打开这个文件的完整路径

路径是相对的;images_to_rename我在所在的同一目录中运行 python 脚本

from os import path, listdir

# Dir where the images are
assets = "images_to_rename"
# create a list of files in that dir
filelist = listdir(assets)

for file in filelist:
    # join path and file name
    joined_name = path.join(assets, file)
    print(joined_name)

假设该文件夹具有panorama.pnghouse.png。当我在 Windows 上打印时,我得到images_to_rename\\panorama.png,这是错误的,因为它应该是images_to_rename\panorama.png. path.join如果无法在 win 和 OSX 上正确使用相同的代码,则不确定使用的意义何在。

我可以通过在调用时用替换\\替换来解决,但我希望避免使用路径连接。我错过了什么吗?\path.join

标签: python

解决方案


推荐阅读