如何输出文件中的每一行python

如何输出文件中的每一行python

本文介绍了如何输出文件中的每一行python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  应该在for循环之外。 

其次,在循环之前,您只调用一次 readline 。那只读第一行。诀窍是,在Python中,文件充当迭代器,因此您可以迭代文件而不必调用任何方法,每次迭代都会有一行:

如果data.find('!masters')!= -1:
f = open('masters.txt')
在f:$中的行,$

  b $ b print line,
sck.send('PRIVMSG'+ chan ++ line)
f.close()

最后,你指的是循环内的变量 lines 我假设你的意思是指行。



编辑:哦,你需要缩进 if 语句。


     if data.find('!masters') != -1:
         f = open('masters.txt')
         lines = f.readline()
         for line in lines:
               print lines
               sck.send('PRIVMSG ' + chan + " " + str(lines) + '\r\n')
               f.close()

masters.txt has a list of nicknames, how can I print every line from the file at once?. The code I have only prints the first nickname. Your help will be appreciate it. Thanks.

解决方案

Firstly, as @l33tnerd said, f.close should be outside the for loop.

Secondly, you are only calling readline once, before the loop. That only reads the first line. The trick is that in Python, files act as iterators, so you can iterate over the file without having to call any methods on it, and that will give you one line per iteration:

 if data.find('!masters') != -1:
     f = open('masters.txt')
     for line in f:
           print line,
           sck.send('PRIVMSG ' + chan + " " + line)
     f.close()

Finally, you were referring to the variable lines inside the loop; I assume you meant to refer to line.

Edit: Oh and you need to indent the contents of the if statement.

这篇关于如何输出文件中的每一行python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 10:12