How to output each line in a python file

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 aliases, how can I print each line from a file at once ?. The code I printed is only the first alias. Your help will be appreciated. Thanks.

+8
python input file
source share
5 answers

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

Secondly, you only call readline once, before the loop. This is just reading the first line. The trick is that in Python, files act like iterators, so you can iterate over a file without having to call any methods on it, and this 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 referenced the lines variable inside the loop; I assume you meant the line link.

Edit: Oh, and you need to defer the contents of the if .

+19
source share

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') 

Do not close it at each iteration of the loop and print line instead of lines. Also use reading lines to get all lines.

EDIT deleted my other answer - the other in this discussion is a better alternative than mine, so there is no reason to copy it.

Also removed \ n with read (). splitlines ()

+7
source share

You can try this. It does not read all the data in memory at once (using the file object iterator) and closes the file when the code exits block c.

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

If you are using an older version of python (prior to 2.6), you will have to have

 from __future__ import with_statement 
+4
source share

Scroll through the file.

 f = open("masters.txt") lines = f.readlines() for line in lines: print line 
+2
source share

You tried

 for line in open("masters", "r").readlines(): print line 

?

 readline() 

only reads the "string" on the other hand

 readlines() 

reads entire lines and provides a list of all lines.

0
source share

Source: https://habr.com/ru/post/651143/


All Articles