Python错误:“找不到指定的路径”

2024-04-24 16:36:12 发布

您现在位置: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 

Python给了我一个错误,说它找不到指定的路径,因为我的桌面上显然有一个同名的文件夹。可能是操作系统。chidr??我做错什么了?


Tags: inimportforosdeflinerandomresult
2条回答

反斜杠在Python字符串中有特殊的含义。您要么需要将它们加倍,要么使用raw stringr"C:\Users\Mainuser\Desktop\Lab6"(注意开头引号前的r)。

反斜杠是Python字符串中的一个特殊字符,在许多其他语言中也是如此。有很多方法可以解决这个问题,首先是将反斜杠加倍:

"C:\\Users\\Mainuser\\Desktop\\Lab6"

使用原始字符串:

r"C:\Users\Mainuser\Desktop\Lab6"

或者使用os.path.join来构造路径:

os.path.join("c:", os.sep, "Users", "Mainuser", "Desktop", "Lab6")

os.path.join是最安全和最便携的选择。只要你有“c:”硬编码的路径,它不是真正的便携式,但它仍然是最佳实践和良好习惯的发展。

为了正确地生成c:\ Users而不是c:Users,Python os.path.join on Windows提供了一个技巧。

相关问题 更多 >