how to output every line in a file python

后端 未结 5 2106
执笔经年
执笔经年 2021-01-04 04:01
     if data.find(\'!masters\') != -1:
         f = open(\'masters.txt\')
         lines = f.readline()
         for line in lines:
               print lines
               


        
相关标签:
5条回答
  • 2021-01-04 04:37

    You could try this. It doesn't read all of f into memory at once (using the file object's iterator) and it closes the file when the code leaves the with block.

    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're using an older version of python (pre 2.6) you'll have to have

    from __future__ import with_statement
    
    0 讨论(0)
  • 2021-01-04 04:37

    Loop through the file.

    f = open("masters.txt")
    lines = f.readlines()
    for line in lines:
        print line
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-04 04:44

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

    0 讨论(0)
  • 2021-01-04 04:53

    Did you try

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

    ?

    readline() 
    

    only reads "a line", on the other hand

    readlines()
    

    reads whole lines and gives you a list of all lines.

    0 讨论(0)
提交回复
热议问题