【问题标题】:Python error: "cannot find path specified"Python 错误:“找不到指定的路径”
【发布时间】:2013-10-30 20:27:13
【问题描述】:
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??我做错了什么?

【问题讨论】:

  • 始终使用原始字符串:r"C:\Users\Mainuser\Desktop\Lab6"
  • 了解相对寻址。这将允许文件位于 `C:\Users\Mainuser\Desktop` 之外的某个位置
  • @hcwhsa:对这个相当直率的评论稍微解释一下?

标签: python text random path


【解决方案1】:

反斜杠是 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 实际正确的做法。 (path.join 而不是转义)。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2015-11-28
    • 1970-01-01
    • 2016-12-11
    • 2015-08-19
    • 2020-05-27
    • 2017-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多