带枚举的基本 python file-io 变量
python 新手,正在尝试学习文件 i/o 的诀窍。
我正在以这种格式从一个大(200 万行)文件中提取行:
56fr4
4543d
4343d
5irh3
这是我用来返回代码的函数:
def getCode(i):
with open("test.txt") as f:
for index, line in enumerate(f):
if index == i:
code = # what does it equal?
break
return code
一旦索引到达正确的位置(i),我应该使用什么语法设置代码变量?
New to python and trying to learn the ropes of file i/o.
I am working with pulling lines from a large (2 million line) file in this format:
56fr4
4543d
4343d
5irh3
Here is the function I'm using to return a code:
def getCode(i):
with open("test.txt") as f:
for index, line in enumerate(f):
if index == i:
code = # what does it equal?
break
return code
Once the index gets to the right spot (i), what syntax do I use to set the code variable?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
code = line.strip()
将把 code 分配给等于 i 的行号,同时删除尾随的新行。
您还需要稍微更新一下代码
为什么需要
.strip()
是的,“'语言关系',”在我当前的temp.txt中'
code = line.strip()
will assign code to the line number that is equal to i while removing the trailing new line.
you also need to update your code a bit
why you need
.strip()
yes, " 'LINGUISTIC AFFILIATION'," is in my current temp.txt'
enumerate
将一个迭代器转换为另一个迭代器,这样您迭代的内容就成为一对(数字 ID、底层迭代器的原始项)。在我们的例子中:
for index, line in enumerate(f):
f
是文件对象。文件对象是迭代器:它们迭代文件的行。我们将其转换为(行号,文件中的行)对的迭代器。
for 循环语法迭代迭代器,并将(行号,文件中的行)对分配给变量:(索引,行)。这只是将一个元组分配给另一个元组的正常行为。
因此,每次循环时,都会为
index
分配一个行号,并为line
分配文件中相应的行。文件中的行是您想要的(可能带有一些格式),并且line
包含它,所以...如果以上任何内容没有意义,您可能需要重新阅读该语言的介绍。
enumerate
transforms one iterator into another, such that the things you iterate over become pairs of (numeric ID, original item from the underlying iterator).In our case:
for index, line in enumerate(f):
f
is the file object. File objects are iterators: they iterate over lines of the file.We transform that into an iterator over (line number, line from file) pairs.
The
for
loop syntax iterates over the iterator, and assigns the (line number, line from file) pair to the variables: (index, line). This is just the normal behaviour of assigning one tuple to another.So, each time through the loop,
index
gets assigned a line number, andline
gets assigned the corresponding line from the file. The line from the file is what you want (possibly with some formatting), andline
contains it, so...If any of the above didn't make sense, you probably need to re-read an introduction to the language.