Python windows文件路径路径中的空格

Python windows文件路径路径中的空格,python,file,Python,File,我正在使用python进行文件操作 我的文件路径为: filepath = "E:/ABC/SEM 2/testfiles/all.txt" 当我使用python打开文件时,它会告诉我: IOError: No such file: 但是,该文件存在于驱动器上。 这可能是因为windows无法正确使用“SEM 2”,因为它包含空间。 如何处理窗口路径路径中的此类空白?尝试在filepath变量中加双引号 "\"E:/ABC/SEM 2/testfiles/all.txt\"" 检查文件的权

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

我的文件路径为:

filepath = "E:/ABC/SEM 2/testfiles/all.txt"
当我使用python打开文件时,它会告诉我:

IOError: No such file:
但是,该文件存在于驱动器上。
这可能是因为windows无法正确使用“SEM 2”,因为它包含空间。

如何处理窗口路径路径中的此类空白?

尝试在filepath变量中加双引号

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

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

路径中的空白区域没有问题,因为您不使用“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>
Python 2.7.2(默认值,2011年6月12日14:24:46)[MSC v.1500 64位(AMD64)]在wi上
32
有关详细信息,请键入“帮助”、“版权”、“信用证”或“许可证”。
>>>导入操作系统
>>>
>>>os.makedirs(“C:/ABC/sem2/testfiles”)
>>>打开(“C:/ABC/SEM 2/testfiles/all.txt”、“w”)
>>>退出()
C:\Users\Gnibbler>dir“C:\ABC\SEM 2\testfiles”
驱动器C中的卷没有标签。
卷序列号为46A0-BB64
c:\ABC\SEM 2\testfiles目录
2013年2月13日晚上10:20。
2013年2月13日晚上10:20。。
2013年2月13日10:20 PM 0 all.txt
1个文件0个字节
2个目录78929309696个可用字节
C:\Users\Gnibbler>
关闭r“string”中的路径也很好地解决了这个问题

(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)

苹果电脑上的黑客攻击:

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

你是怎么打开文件的?名字中的空格应该没有问题。不难判断问题是否出在空格上(但我不这么认为):只需重命名目录,看看它是否能找到该文件。如果我选择了文件夹名中不包含此类空格的任何文件,则该文件正在正确打开。是否尝试使用正斜杠而不是basckslash?正斜杠工作正常。空间也是如此。你是如何打开文件的?正如gnibbler所演示的,它不是空格,多加引号也无济于事。对我来说,我使用的不是windows 7+anaconda 3.5,如果我使用单引号(')而不是双引号(“),会发生什么?这样行吗
/Volumes/Public/ABY/Documents/Musiq/slumdog\ millonaire/Mausam\ and\ Escape.mp3