【问题标题】:Python 2: AttributeError: 'file' object has no attribute 'strip'Python 2:AttributeError:'file'对象没有属性'strip'
【发布时间】:2013-07-18 13:28:51
【问题描述】:

我有一个名为 new_data.txt.txt 文档。本文档中的所有数据以点分隔。我想在 python 中打开我的文件,将其拆分并放入一个列表中。

output = open('new_data.txt', 'a')
output_list = output.strip().split('.')

但我有一个错误:

AttributeError: 'file' object has no attribute 'strip'

我该如何解决这个问题?

注意:我的程序在 Python 2 上

【问题讨论】:

    标签: python python-2.7 list split


    【解决方案1】:

    首先,你想以读取模式打开文件(你有它在追加模式)

    那你要read()文件:

    output = open('new_data.txt', 'r') # See the r
    output_list = output.read().strip().split('.')
    

    这将获取文件的全部内容。

    当前您正在使用文件对象(因此出现错误)。


    更新:似乎这个问题自最初以来获得了更多的意见。打开文件时,with ... as ... 结构应该像这样使用:

    with open('new_data.txt', 'r') as output:
        output_list = output.read().strip().split('.')
    

    这样做的好处是不需要显式关闭文件,如果控制序列中出现错误,python会自动为你关闭文件(而不是文件在出错后保持打开状态)

    【讨论】:

    • 这是迄今为止最简单的方法。
    猜你喜欢
    • 2013-07-19
    • 2017-05-03
    • 2020-03-25
    • 2016-08-11
    • 2021-07-10
    • 1970-01-01
    • 2020-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多