0

I'm trying to learn Python in my free time, and my textbook is not covering anything about my error, so I must've messed up badly somewhere. When I try to open and read a text file through notepad (on Windows) with my code, it produces the error. My code is:

def getText():
    infile = open("C:/Users/****/AppData/Local/Programs/Python/Python35-32/lib/book.txt" , "r")
    allText = infile.read()
    return allText

If it's necessary, here is the rest of my code so far:

def inspectWord(theWord,wList,fList):
    tempWord = theWord.rstrip("\"\'.,`;:-!")
    tempWord = tempWord.lstrip("\"\'.,`;:-!")
    tempWord = tempWord.lower()
    if tempWord in wList:
        tIndex = wList.index(tempWord)
        fList[tIndex]+=1
    else:
        wList.append(tempWord)
        fList.append(1)

def main():
     myText = getText()
     print(myText)

main()

I'd greatly appreciate any advice, etc.; I cannot find any help for this. Thanks to anyone who responds.

  • 2
    Err No. 2 means python can’t find the file. Are you sure the path to the file is correct? – 2ps Oct 14 '16 at 04:44
  • You presumably have the wrong file path or the file does not exist. – Lost Oct 14 '16 at 04:47
  • I looked at the text file's properties and found it because I had named it "book.txt" and it was already a .txt file, file was apparently "book.txt.txt". I just took out one of the .txts, but now it's giving me an error in the traceback saying: "C:\Users\****\AppData\Local\Programs\Python\Python35-32\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 13261: character maps to – GottaLoveArchery Oct 14 '16 at 04:56

2 Answers2

0

To open a unicode file, you can do the following

import codecs

def getText():
    with codecs.open("C:/Users/****/AppData/Local/Programs/Python/Python35-32/lib/book.txt" , "r", encoding='utf8') as infile:
        allText = infile.read()
    return allText

See also: Character reading from file in Python

Community
  • 1
  • 1
2ps
  • 15,099
  • 2
  • 27
  • 47
0

First of all, I recommend you to use relative path, not absolute path. It is simpler and will make your life easier especially now that you just started to learn Python. If you know how to deal with commandline, run a new commandline and move to the directory where your source code is located. Make a new text file there and now you can do something like

 f = open("myfile.txt")


Your error indicates that there is something wrong with path you passed to builtin function open. Try this in an interactive mode,

>> import os
>> os.path.exists("C:/Users/****/AppData/Local/Programs/Python/Python35-32/lib/book.txt")

If this returns False, there is nothing wrong with your getText fuction. Just pass a correct path to open function.