Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to output every line in a file python

Tags:

python

file

input

     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.

like image 234
SourD Avatar asked Jan 17 '11 03:01

SourD


2 Answers

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.

like image 119
mgiuca Avatar answered Oct 09 '22 21:10

mgiuca


You probably want something like:

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

Don't close it every iteration of the loop and print line instead of lines. Also use readlines to get all the lines.

EDIT removed my other answer - the other one in this discussion is a better alternative than what I had, so there's no reason to copy it.

Also stripped off the \n with read().splitlines()

like image 30
NG. Avatar answered Oct 09 '22 22:10

NG.