How to loop until the rows of a given .txt file run out

1

I would like to make a basic loop system for example, open the file that the user typed after using an if for as long as you have lines in the file to loop with other codes

    
asked by anonymous 27.04.2017 / 02:49

2 answers

4

In Python, the object itself that represents an open file is made to work directly with a loop as you speak. For example, a program to print each line of a file is simply:

nome = input("Digite o nome do arquivo: ")
with open(nome) as arq:
    for linha in arq:
        print(linha)

In other words: you use the direct file in the command for of Python - when the file is finished it leaves for . (And in this case, since we have with , it exits with as well and already closes the file).

This happens simply because the object file implements the "iterator protocol" - with the methods __iter__ and __next__ . Any object that has these methods (implemented correctly) can work directly on the for command.

    
28.04.2017 / 02:05
2

I do not like to ask for file names interactively; I prefer to create scripts that receive parameters via the line of command. In this sense I recommend the module fileinput :

#!/usr/bin/python
# -*- coding=utf-8 -*-

import fileinput
for linha in fileinput.input():
   linha=linha.strip()
   #processa linha

In this way the script works like a normal Unix command, and in the line of command we can give zero (stdin, pipes) or more files to process.

See also the always useful functions fileinput.filename() close() isfirstline() lineno() filelineno() nextfile()

    
28.04.2017 / 13:12