如何在Python中使用文本文件创建列表

huangapple go评论70阅读模式
英文:

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(&#39;todos.txt&#39;, &#39;r&#39;)
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 &quot;D:\py projects\experiments.py&quot;, line 12, in &lt;module&gt;
todos.append(todo)
AttributeError: &#39;str&#39; object has no attribute &#39;append&#39;

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(&quot;todos.txt&quot;, &quot;r&quot;) 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()

huangapple
  • 本文由 发表于 2023年3月9日 19:39:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/75684100.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定