从网络驱动器(windows)上的目录检索内容

2024-05-23 14:46:56 发布

您现在位置:Python中文网/ 问答频道 /正文

在Windows上显示来自网络驱动器的文件时遇到问题。

path = "\\\\nexus\\File Server\\Technical\\MyDrive\\Software\\Releases\\%s\\%s\\" %(release, module)

其中\\nexus\是网络驱动器。

我的主要问题是,如果用户输入了正确的变量,则无法显示所请求目录的内容(“module”的内容)。

我试过的东西

  1. os.listdir(path)
    上面这一行的问题是,它返回一个windows错误[123],即一个找不到目录错误。这是因为listdir()似乎是所有反斜杠的两倍 导致:

    "\\\\\\\\nexus\\File Server\\\\Technical\\\\MyDrive\\\\Software\\\\Releases\\\\release\\\\module\\\\"
    
  2. print(glob.glob(path))
    我真的不知道它是如何工作的:P但它似乎只是显示提供的目录,而不是结束目录的内容

     \\nexus\File Server\Technical\MyDrive\Software\Releases\release\module\"
    

我见过一个os.walk但是我不确定它是如何工作的,因为它如何定义什么是基本目录和路径的其余部分

额外说明:“module”的内容将始终是一个zip文件,而且该目录通常最多包含五个zip文件。


Tags: 文件path网络目录nexus内容releaseserver
3条回答

这个对我有用:

os.listdir('\\\\server\folder\subfolder\etc')

(在Win7 64b上使用Python 2.7 32b)

解决此问题的方法如下:

os.listdir('\\networkshares\\folder1\\folder2\\folder3')

这意味着您必须使用双斜杠而不是单斜杠。

刚刚在我的XP电脑上测试过,Python 2.7,SMB共享\\myshare

os.listdir('\\\\myshare') # Fails with "WindowsError: [Error 53] The network path was not found"

os.listdir('\\\\myshare/folder') # Succeeds

我认为有些混乱可能是由于WindowsError显示路径的repr()而不是实际路径-

>>> repr(path)
"'\\\\myshare'"
>>> str(path)
'\\myshare'

如果这是Python 3&unicode问题,我建议首先尝试修复字符串:

path = "\\\\myshare\folder"
path = bytes(path, "utf-8").decode("unicode_escape")
print os.listdir(path)

(不幸的是,由于我没有安装Python 3,所以我无法测试它,但是请让我知道它是否有效,我将编辑我的答案)

相关问题 更多 >