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

user2928929
  • 205
  • 4
  • 5
  • 8

2 Answers2

13

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.

Community
  • 1
  • 1
Peter DeGlopper
  • 36,326
  • 7
  • 90
  • 83
3

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

NPE
  • 486,780
  • 108
  • 951
  • 1,012