Python 2: AttributeError: 'file' 对象没有属性 'strip'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17743083/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python 2: AttributeError: 'file' object has no attribute 'strip'
提问by Michael
I have a .txtdocument called new_data.txt. All data in this document separated by dots. I want to open my file inside python, split it and put inside a list.
我有一个名为new_data.txt的.txt文档。本文档中的所有数据以点分隔。我想在 python 中打开我的文件,将其拆分并放入一个列表中。
output = open('new_data.txt', 'a')
output_list = output.strip().split('.')
But I have an error:
但我有一个错误:
AttributeError: 'file' object has no attribute 'strip'
How can I fix this?
我怎样才能解决这个问题?
Note: My program is on Python 2
注意:我的程序在 Python 2 上
采纳答案by TerryA
First, you want to open the file in read mode (you have it in append mode)
首先,你想以读取模式打开文件(你在追加模式下打开它)
Then you want to read()
the file:
然后你想要read()
文件:
output = open('new_data.txt', 'r') # See the r
output_list = output.read().strip().split('.')
This will get the whole content of the file.
这将获得文件的全部内容。
Currently you are working with the file object (hence the error).
目前您正在使用文件对象(因此出现错误)。
Update: Seems like this question has received a lot more views since its initial time. When opening files, the with ... as ...
structure should be used like so:
更新:似乎这个问题自最初提出以来已经收到了更多的观点。打开文件时,with ... as ...
应该像这样使用结构:
with open('new_data.txt', 'r') as output:
output_list = output.read().strip().split('.')
The advantage of this is that there's no need to explicitly close the file, and if an error ever occurs in the control sequence, python will automatically close the file for you (instead of the file being left open after error)
这样做的好处是不需要显式关闭文件,如果控制序列中出现错误,python会自动为你关闭文件(而不是文件出错后保持打开状态)