【问题标题】:Can't get python to read my .txt file on OS X无法让 python 在 OS X 上读取我的 .txt 文件
【发布时间】:2013-03-11 09:15:43
【问题描述】:

我试图让 IDLE 读取我的 .txt 文件,但由于某种原因它不会。我在学校尝试过同样的事情,使用带有记事本的 Windows 计算机运行良好,但现在使用带 IDLE 的 Mac 无法读取(或找到)我的 .txt 文件。

我确保它们位于同一个文件夹/目录中,并且文件格式为纯文本,但仍然出现错误。这是我使用的代码:

def loadwords(filename):

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

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

这是我输入文件名“test.txt”并按回车后得到的错误:

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)

【问题讨论】:

    标签: osx-snow-leopard python textedit


    【解决方案1】:

    您看到的错误意味着您的 Python 解释器尝试将文件加载为 ASCII 字符,但您尝试读取的文本文件不是 ASCII 编码。它可能是 UTF-8 编码的(最近的 OSX 系统中的默认值)。

    将编码添加到open 命令应该会更好:

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

    另一种纠正方法是使用您的文件返回 TextEdit,然后选择 Duplicate(或 另存为 shift-cmd-S) 您可以在其中再次保存文件,但这次选择 ASCII 编码。如果 ASCII 不存在,您可能需要在编码选项列表中添加它。

    这个other question and accepted answer 提供了一些关于选择您正在阅读的文件的编码方式的更多想法。

    【讨论】:

    • open() 调用中缺少逗号。
    • @NiklasR 在我的 Snow Leopard,python 2.6 上,open 我写的命令工作正常。
    • 试试open(filename, "rutf8")。这就是您的代码最终的结果,并且失败并显示“无效模式('rutf8')”。 编辑:等等,我们是在谈论 Python 2 还是 3?
    【解决方案2】:

    您需要使用适当的编码打开文件。此外,您应该从方法中返回一些内容,否则您将无法对文件执行任何操作。

    试试这个版本:

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

    这一行[line for line in f if line.strip()]list comprehension。这是以下的简短版本:

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

    【讨论】:

      【解决方案3】:

      textfile = "textfile.txt"

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

      【讨论】:

        【解决方案4】:

        此编码限制仅限于 python 版本 2.*

        如果您的 MAC 运行的是 Python 版本 3.*,您不必添加额外的编码部分来对 txt 文件进行编码。

        下面的函数将直接在python 3中运行,无需任何编辑。

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-07-03
          • 1970-01-01
          • 2018-03-22
          • 1970-01-01
          • 2013-09-17
          • 2020-04-17
          相关资源
          最近更新 更多