[英]Reading lines from a file in Jython
Ok, I know this is going to sound like a homework question (because it kind of is), but our lecturer has thrown us in the deep end with this and I need a little help, my google-fu is failing. 好的,我知道这听起来像是一个家庭作业问题(因为有点像),但是我们的讲师对此深有感触,我需要一点帮助,我的Google-fu失败了。 As part of an assignment I need to read in data from a text file, and copy each line of the text file into an array/list.
作为作业的一部分,我需要从文本文件中读取数据,并将文本文件的每一行复制到数组/列表中。 What I've done is not working.
我做的没有用。 What I have so far:
到目前为止,我有:
def main():
file = open(pickAFile())
lines = []
index = 0
for line in file:
lines[index] = line
index = index + 1
But this comes back with: The error value is: list assignment index out of range Sequence index out of range. 但这又返回了: 错误值为:列表分配索引超出范围序列索引超出范围。 The index you're using goes beyond the size of that data (too low or high).
您使用的索引超出了该数据的大小(太低或太高)。 For instance, maybe you tried to access OurArray[10] and OurArray only has 5 elements in it.
例如,也许您尝试访问OurArray [10],而OurArray中仅包含5个元素。
Any help would be most welcome! 任何帮助将是最欢迎的!
The problem is in the line lines[index] = line
. 问题出在line
lines[index] = line
。 There is nothing in lines[0]
in the first iteration. 在第一次迭代中,
lines[0]
没有任何内容。
You need to change this line to lines.append(line)
, and you don't need to keep track after index
, so your whole code should look like: 您需要将此行更改为
lines.append(line)
,并且无需跟踪index
,因此整个代码应如下所示:
def main():
file = open(pickAFile())
lines = []
for line in file:
lines.append(line)
append
adds the parameter that it receives to the last index in the list that it is called with, see the docs . append
将接收到的参数添加到调用列表的最后一个索引中,请参阅docs 。
You cannot extend list
like this, if your list is empty ( lines = []
), then lines[index]
is trying to access a non existing index and thus throws an error. 您不能像这样扩展
list
,如果列表为空( lines = []
),则lines[index]
试图访问不存在的索引,从而引发错误。
If you want to append something to your list, use the append function: 如果要将某些内容追加到列表中,请使用append函数:
lines.append(line)
But if you want to read all the lines in a file, you'd better use the readlines
method: 但是,如果您想读取文件中的所有行,则最好使用
readlines
方法:
lines = file.readlines()
To read file into list you can try: 要将文件读入列表,您可以尝试:
with open("file.txt") as f:
lines = f.readlines()
or 要么
lines = [line for line in open("file.txt")]
Here each line will have \\n
characters. 在这里,每行将有
\\n
字符。 To remove that use, line.rtrim('\\n')
要删除该用途,
line.rtrim('\\n')
使用line.rtrim('\\n')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.