简体   繁体   中英

Can't get python to read my .txt file on OS X

I'm trying to get IDLE to read my .txt file but for some reason it won't. I tried this same thing at school and it worked fine using a Windows computer with Notepad, but now using my Mac with IDLE won't read (or find) my .txt file.

I made sure they were in the same folder/directory and that the file was formatted in plain text, still I get errors. Here's the code I was using:

def loadwords(filename):

   f = open(filename, "r")
   print(f.read())
   f.close()
   return

filename = input("enter the filename: ")
loadwords(filename)

and here is the error I got after I enter the file name "test.txt" and press enter:

Traceback (most recent call last):
  File "/Computer Sci/My programs/HW4.py", line 8, in <module>
    loadwords(filename)
  File "/Computer Sci/My programs/HW4.py", line 4, in loadwords
    print(f.read())
  File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/encodings/ascii.py", line 26, in decode
    return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128)

The error you see means your Python interpreter tries to load the file as ASCII chars, but the text file you're trying to read is not ASCII encoded . It's probably UTF-8 encoded (the default in recent OSX systems).

Adding the encoding to the open command should work better:

f = open(filename, "r" "utf8")

Another way to correct that, would be to go back to TextEdit with your file and then select Duplicate (or Save as shift-cmd-S ) where you'll be able to save your file again, but this time choosing the ASCII encoding. Though you might need to add ASCII in the encodings option list if it is not present.

This other question and accepted answer provides some more thoughts about the way to choose the encoding of the file you're reading.

You need to open the file with the appropriate encoding. Also, you should return something from the method otherwise you won't be able to do anything with the file.

Try this version:

def loadwords(filename):
    with open(filename, 'r', encoding='utf8') as f:
         lines = [line for line in f if line.strip()]
    return lines

filename = input('Enter the filename: ')
file_lines = loadwords(filename)

for eachline in file_lines:
    print('The line is {}'.format(eachline))

This line [line for line in f if line.strip()] is a list comprehension . It is the short version of:

for line in f:
   if line.strip(): # check for blank lines
       lines.append(line)

textfile = "textfile.txt"

file = open(textfile, "r", encoding = "utf8")
read = file.read()
file.close()
print(read)

This encoding limitiation was limited to python version 2.*

If your MAC is running a Python version 3.* you do not have to add the extra encoding part to encode the txt file.

The below function will directly run in python 3 without any edit.

def loadwords(filename):
f = open(filename, "r")
print(f.read())
f.close()
return
filename = input("enter the filename: ")
loadwords(filename)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM