【问题标题】:Opening files from filepaths on windows从 Windows 上的文件路径打开文件
【发布时间】:2019-09-27 07:31:57
【问题描述】:

我尝试定义一个函数,它将获取文件路径并将其转换为字符串。 这是我想出的辩护:

    def get_book(file_path):
        '''Takes a file path and returns the entire book as a string.'''
        with open(file_path, 'r', 'utf-8') as infile:
            content = infile.read()
            return content

    AnnaKarenina = get_book('../Python/Data/books/AnnaKarenina.txt')

我现在得到 TypeError: an integer is required (got type str)

我也尝试使用 os.path、不同种类的斜线和其他技巧来使用 windows 打开文件,但都返回找不到文件的错误。

有谁知道我做错了什么?

【问题讨论】:

    标签: windows file typeerror


    【解决方案1】:

    open函数的编码参数是一个命名参数,所以你必须这样指定:

     def get_book(file_path):
            '''Takes a file path and returns the entire book as a string.'''
            with open(file_path, 'r', encoding='utf-8') as infile:
                content = infile.read()
                return content
    
    AnnaKarenina = get_book('../Python/Data/books/AnnaKarenina.txt')
    

    【讨论】:

    • 澄清一下,encoding 不是仅关键字参数,而是第四个位置参数,OP 将其作为第三个参数buffering 传递,它需要一个整数。将encoding 作为关键字参数传递可以避免传递buffering 的值。
    • 仅供参考,惯用的 Python 风格不会在关键字参数分配周围使用空格,例如它是encoding='utf-8',除非它是函数定义中的注释参数,例如parameter: str = None。参考PEP 8,“表达式和语句中的空格”->“其他建议”。
    • 感谢这些建议。我编辑了答案以尊重 PEP8
    猜你喜欢
    • 1970-01-01
    • 2014-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-05
    • 1970-01-01
    • 2012-07-13
    相关资源
    最近更新 更多