Python错误:";找不到指定的路径";
Python给了我一个错误,说它找不到指定的路径,而我的桌面上显然有一个同名的文件夹。可能是os.chidr??我做错了什么?反斜杠在Python字符串中具有特殊意义。您需要将它们加倍,或者使用:Python错误:";找不到指定的路径";,python,text,random,path,Python,Text,Random,Path,Python给了我一个错误,说它找不到指定的路径,而我的桌面上显然有一个同名的文件夹。可能是os.chidr??我做错了什么?反斜杠在Python字符串中具有特殊意义。您需要将它们加倍,或者使用:r“C:\Users\Mainuser\Desktop\Lab6”(请注意开头引号之前的r。反斜杠是Python字符串中的一个特殊字符,在许多其他语言中也是如此。有很多方法可以解决这个问题,首先是将反斜杠加倍: import os import random os.chdir("C:\Users\Ma
r“C:\Users\Mainuser\Desktop\Lab6”
(请注意开头引号之前的r
。反斜杠是Python字符串中的一个特殊字符,在许多其他语言中也是如此。有很多方法可以解决这个问题,首先是将反斜杠加倍:
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
使用原始字符串:
"C:\\Users\\Mainuser\\Desktop\\Lab6"
或者使用os.path.join
构建路径:
r"C:\Users\Mainuser\Desktop\Lab6"
os.path.join
是最安全、最便携的选择。只要路径中有“c:”硬编码,它就不是真正的可移植性,但它仍然是最佳实践和良好习惯
为了找到生成c:\Users而不是c:Users的正确方法,我们需要一点提示。始终使用原始字符串:
r“c:\Users\Mainuser\Desktop\Lab6”
了解相关寻址。这将允许文件位于'C:\Users\Mainuser\Desktop`@hcwhsa之外的某个位置:对这条相当直率的评论做一点解释?+1,了解正确的操作方法。(path.join而不是转义)。
os.path.join("c:", os.sep, "Users", "Mainuser", "Desktop", "Lab6")