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

时间:2013-10-30 20:27:13

标签: python text random path

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给我一个错误,说它无法找到指定的路径,当我在桌面上清楚地有一个带有该名称的文件夹时。它可能是os.chidr ??我做错了什么?

2 个答案:

答案 0 :(得分:6)

反斜杠是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:”它就不是真正可移植的,但它仍然是最好的习惯和良好的习惯。

Python os.path.join on Windows的方式提示,以正确的方式生成c:\ Users而不是c:Users。

答案 1 :(得分:2)

反斜杠在Python字符串中有特殊含义。您需要将它们加倍或使用raw stringr"C:\Users\Mainuser\Desktop\Lab6"(请在开头报价之前注明r)。

相关问题