Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python error: "cannot find path specified"

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

like image 544
user2928929 Avatar asked Oct 30 '13 20:10

user2928929


People also ask

What does it mean when it says the system Cannot find the path specified?

One of the reasons why the system cannot find the path specified is that the folder or file gets lost. Please exit Command Prompt and check whether the folder or file is still in PC. If the folder or file is really lost, please get them back.

What is PATH () in Python?

PYTHONPATH is an environment variable which the user can set to add additional directories that the user wants Python to add to the sys. path directory list. In short, we can say that it is an environment variable that you set before running the Python interpreter.


1 Answers

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:\Users\Mainuser\Desktop\Lab6"

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.

like image 104
Peter DeGlopper Avatar answered Oct 12 '22 22:10

Peter DeGlopper