Python windows文件路径中的空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14852140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:39:27  来源:igfitidea点击:

whitespaces in the path of windows filepath

pythonfile

提问by sam

I am working on file operations using python.

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

I have a filepath as :

我有一个文件路径:

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

when I am opening the file using python, it says me :

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

IOError: No such file:

but, the file is present on the drive.
It may be because windows cannnot take "SEM 2" properly as it contains space.
How can I deal with such whitespaces in the path of window path?

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

采纳答案by John La Rooy

There is no problem with whitespaces in the path since you're not using the "shell" to open the file. Here is a session from the windows console to prove the point. You're doing something else wrong

路径中的空格没有问题,因为您没有使用“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>

回答by valentinos

Try putting double quotes in your filepath variable

尝试在文件路径变量中放置双引号

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

Check the permissions of the file or in any case consider renaming the folder to remove the space

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

回答by billmanH

path = r"C:\Users\mememe\Google Drive\Programs\Python\file.csv"

Closing the path in r"string" also solved this problem very well.

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

回答by user5252970

This solution worked for me: "putting double quotes"

这个解决方案对我有用:“放双引号”

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