Python 错误:“找不到指定的路径”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19693175/
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
Python error: "cannot find path specified"
提问by user2928929
import os
import random
os.chdir("C:\Users\Mainuser\Desktop\Lab6")
#Am i supposed to have a os.chdir?
# I think this is what's giving the error
#how do i fix this?
def getDictionary():
result = []
f = open("pocket-dic.txt","r")
for line in f:
result = result + [ line.strip() ];
return result
def makeText(dict, words=50):
length = len(dict)
for i in range(words):
num = random.randrange(0,length)
words = dict[num]
print word,
if (i+1) % 7 == 0:
print
Python gives me an error saying it cannot find the path specified, when i clearly have a folder on my desktop with that name. It might be the os.chidr?? what am i doing wrong?
Python 给我一个错误,说它找不到指定的路径,当我的桌面上显然有一个具有该名称的文件夹时。它可能是 os.chidr?? 我究竟做错了什么?
采纳答案by Peter DeGlopper
Backslash is a special character in Python strings, as it is in many other languages. There are lots of alternatives to fix this, starting with doubling the backslash:
反斜杠是 Python 字符串中的一个特殊字符,就像在许多其他语言中一样。有很多替代方法可以解决这个问题,首先是将反斜杠加倍:
"C:\Users\Mainuser\Desktop\Lab6"
using a raw string:
使用原始字符串:
r"C:\Users\Mainuser\Desktop\Lab6"
or using os.path.join
to construct your path instead:
或使用os.path.join
来构建您的路径:
os.path.join("c:", os.sep, "Users", "Mainuser", "Desktop", "Lab6")
os.path.join
is the safest and most portable choice. As long as you have "c:" hardcoded in the path it's not really portable, but it's still the best practice and a good habit to develop.
os.path.join
是最安全、最便携的选择。只要你在路径中硬编码了“c:”,它就不是真正可移植的,但它仍然是最佳实践和养成的好习惯。
With a tip of the hat to Python os.path.join on Windowsfor the correct way to produce c:\Users rather than c:Users.
使用Windows上的Python os.path.join来说明生成 c:\Users 而不是 c:Users 的正确方法。
回答by NPE
Backslashes have special meaning inside Python strings. You either need to double them up or use a raw string: r"C:\Users\Mainuser\Desktop\Lab6"
(note the r
before the opening quote).
反斜杠在 Python 字符串中具有特殊含义。您要么需要将它们加倍,要么使用原始字符串:(r"C:\Users\Mainuser\Desktop\Lab6"
注意r
开头引号之前的内容)。