英文:
how to create list using text file in python
问题
文件 = open('todos.txt', 'r')
待办事项 = 文件.readline()
文件.close()
当我在程序的后面尝试使用它时,我得到以下错误:
输入一个待办事项 :dance
Traceback (most recent call last):
File "D:\py projects\experiments.py", line 12, in <module>
待办事项.append(待办事项)
AttributeError: 'str' object has no attribute 'append'
我必须创建一个列表,所以我需要待办事项作为一个列表,但这并没有发生。
英文:
file = open('todos.txt', 'r')
todos = file.readline()
file.close()
When I then try to use this later in my program, I get the following error:
Enter a todo :dance
Traceback (most recent call last):
File "D:\py projects\experiments.py", line 12, in <module>
todos.append(todo)
AttributeError: 'str' object has no attribute 'append'
I have to create a list so i needed todos as a list which is not happening
答案1
得分: 1
你可以使用 readlines
来获取行的列表,如下所示:
with open("todos.txt", "r") as f:
todos = f.readlines()
在你的解决方案中,对 readline
的调用会将一行作为字符串获取,这就是为什么你无法追加到它上面的原因。
英文:
You can use readlines
to get a list of lines, like so:
with open("todos.txt", "r") as f:
todos = f.readlines()
In your solution, the call to readline
gets one line as a string, which is why you can't append to it.
答案2
得分: 0
file.readline
是字符串类型,字符串没有append
方法。而file.readlines
是列表类型,并且有append
方法。
你需要使用todos = file.readlines()
而不是todos = file.readline()
。
英文:
file.readline
is of type string and string doesn't have append
method.
whereas file.readlines
if of type list and have append
method.
you need to use todos = file.readlines()
instead of todos = file.readline()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论