繁体   English   中英

如何定义要从文件读入的行的长度

[英]How to define length of lines to read in from a file

我正在从Python文件中读取行。 这是我的代码:

with open('words','rb') as f:
    for line in f:

有没有办法定义我想要使用的行数? 比方说,文件中的前1000行?

你可以使用enumerate()

with open('words','rb') as f:
    for i, line in enumerate(f):
        if i >= 1000:
            break
        # do work for first 1000 lines

使变量计数。 我在下面用过我。 该值将在每次迭代中递增。 当值达到999即1000次时,你可以在那里做东西

i = 0
with open('words','rb') as f:
   for line in f:
      if(i<1000):
         #do stuffs
         i = i+1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM