【问题标题】:whitespaces in the path of windows filepathwindows文件路径路径中的空格
【发布时间】:2013-02-13 11:09:21
【问题描述】:

我正在使用 python 进行文件操作。

我有一个文件路径:

filepath = "E:/ABC/SEM 2/testfiles/all.txt"

当我使用 python 打开文件时,它说我:

IOError: No such file:

但是,该文件存在于驱动器上。
这可能是因为 Windows 无法正确获取“SEM 2”,因为它包含空间。
如何处理窗口路径路径中的此类空格?

【问题讨论】:

  • 你是如何打开文件的?名称中的空格应该没有问题。
  • 不难判断是不是空间问题(但我不这么认为):重命名目录看看能不能找到文件
  • 如果我在文件夹名称中选择任何不包含此类空格的文件,它会正确打开文件
  • 您是否尝试过使用正斜杠而不是反斜杠?
  • 正斜杠工作正常。空间也是如此。您是如何尝试打开文件的?

标签: python file


【解决方案1】:
path = r"C:\Users\mememe\Google Drive\Programs\Python\file.csv"

关闭r"string"中的路径也很好的解决了这个问题。

【讨论】:

  • 不适合我,我用的是 windows 7 + anaconda 3.5
  • 如果我使用单引号(')而不是双引号(“)会发生什么?会起作用吗
【解决方案2】:

路径中的空格没有问题,因为您没有使用“shell”打开文件。这是一个来自 Windows 控制台的会话来证明这一点。你做错了什么

Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on wi
32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>>
>>> os.makedirs("C:/ABC/SEM 2/testfiles")
>>> open("C:/ABC/SEM 2/testfiles/all.txt","w")
<open file 'C:/ABC/SEM 2/testfiles/all.txt', mode 'w' at 0x0000000001D95420>
>>> exit()

C:\Users\Gnibbler>dir "C:\ABC\SEM 2\testfiles"
 Volume in drive C has no label.
 Volume Serial Number is 46A0-BB64

 Directory of c:\ABC\SEM 2\testfiles

13/02/2013  10:20 PM    <DIR>          .
13/02/2013  10:20 PM    <DIR>          ..
13/02/2013  10:20 PM                 0 all.txt
               1 File(s)              0 bytes
               2 Dir(s)  78,929,309,696 bytes free

C:\Users\Gnibbler>

【讨论】:

    【解决方案3】:

    尝试在文件路径变量中添加双引号

    "\"E:/ABC/SEM 2/testfiles/all.txt\""
    

    检查文件的权限或在任何情况下考虑重命名文件夹以删除空间

    【讨论】:

    • 正如 gnibbler 所展示的,这不是空格,更多的引号也无济于事。
    【解决方案4】:

    Mac 上的 hack:

    path = '/Volumes/Public/ABY/Documents/Musiq/slumdog millonaire/Mausam and Escape.mp3'
    nPath = path.replace(' ', '\\ ')
    print(nPath)
    

    输出:

    /Volumes/Public/ABY/Documents/Musiq/slumdog\ millonaire/Mausam\ and\ Escape.mp3
    

    【讨论】:

    • 简单易用的解决方案,在 Windows 上也能完美运行
    【解决方案5】:

    (WINDOWS - AWS 解决方案)
    通过在文件和路径周围加上三引号解决了 Windows。
    优点:
    1) 防止被悄悄忽略的排除。
    2) 包含空格的文件/文件夹将不再出现错误。

        aws_command = 'aws s3 sync """D:/""" """s3://mybucket/my folder/"  --exclude """*RECYCLE.BIN/*""" --exclude """*.cab""" --exclude """System Volume Information/*""" '
    
        r = subprocess.run(f"powershell.exe {aws_command}", shell=True, capture_output=True, text=True)
    

    【讨论】:

      猜你喜欢
      • 2017-10-18
      • 2015-06-13
      • 2012-05-09
      • 2014-09-07
      • 2011-11-27
      • 2013-08-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-10
      相关资源
      最近更新 更多