Python error: "cannot find path specified"

Question:

import os
import random

os.chdir("C:UsersMainuserDesktopLab6")

#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?

Asked By: user2928929

||

Answers:

Backslashes have special meaning inside Python strings. You either need to double them up or use a raw string: r"C:UsersMainuserDesktopLab6" (note the r before the opening quote).

Answered By: NPE

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:

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

using a raw string:

r"C:UsersMainuserDesktopLab6"

or using os.path.join to construct your path instead:

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.

With a tip of the hat to Python os.path.join on Windows for the correct way to produce c:Users rather than c:Users.

Answered By: Peter DeGlopper
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.