【问题标题】:Read file without extension from shared drive in Python在Python中从共享驱动器读取没有扩展名的文件
【发布时间】:2019-10-17 06:12:24
【问题描述】:

我在从共享驱动器访问和读取没有扩展名的文件(内部是一个 json,需要以某种方式读取它,但我无法访问它)时遇到困难。

这是我迄今为止尝试过的:

第一次尝试:

open(r"X:\\shared_drive\Notes").read() 在这个我收到FileNotFoundError: [Errno 2] No such file or directory:

第二次尝试:

with open(r"\\DESKTOP-xxx\shared_drive\Notes", 'r') as f:
      f.read()

在这个我收到OSError: [Errno 22] Invalid argument:

【问题讨论】:

  • 我不知道 Python 是否可以使用共享驱动器,但我会从 os.listdir() 开始检查 Python 在文件夹中看到的文件名。也许您的文件名称为 Notes.txt,但 Windows 隐藏扩展名,您只看到 Notes
  • 很确定 os.listdir() 不适用于共享驱动器。它找不到路径,或者我没有正确输入它。当我使用带有远程主机凭据的 WMI 协议时,我可以在 for diskDrive in c.Win32_Share(): print(diskDrive) 中列出它。
  • 我会从os.listdir(r'X:') 开始,然后是os.listdir(r'X:\shared_drive'),等等。
  • @furas 找不到驱动器X:

标签: python file shared


【解决方案1】:

而不是将路径写成:

\\DESKTOP-xxx\shared_drive\Notes

您是否尝试过使用os 包:

import os.path
file_to_open = os.path.join("DESKTOP-xxx", "shared_drive", "Notes")
f = open(file_to_open)

pathlib:

from pathlib import Path
data_folder = Path("//DESKTOP-xxx/shared_drive/Notes")
file_to_open = data_folder / "Notes"
f = open(file_to_open)

【讨论】:

  • 是的,我尝试了os 包。在您提供的第一个文件中找不到文件FileNotFoundError: [Errno 2] No such file or directory,第二个文件显示OSError: [Errno 22] Invalid argument。这可能与驱动器权限和身份验证有关吗??
  • 尝试 data_folder = Path("\\\\DESKTOP-xxx/shared_drive/Notes")
  • 还是OSError: [Errno 22] Invalid argument
  • 路径名构造不是这里的问题;他们正确地使用了原始字符串文字。
猜你喜欢
  • 1970-01-01
  • 2012-10-16
  • 1970-01-01
  • 2016-03-24
  • 2013-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多