How to run a loop until the lines of a given.txt file end

Asked

Viewed 534 times

1

I would like to make a basic loop system for example, open the file that the user typed then use an if for while having lines in the file run a loop with other code

  • Search by the method readlines in Python.

  • right go take a look.

  • 1

    In fact, since many versions ago, qunado files have become direct iterable, use the readlines is no longer a good idea: http://stupidpythonideas.blogspot.com.br/2013/06/readlines-considered-silly.html. : linhas = list(open("meuarq.txt")) - without the readlines,

2 answers

4


In Python, the object itself representing an open file is made to work directly with a loop as you speak. For example, a program to print each row 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 python - when the file is finished it leaves the for. (And in that case, how do we get the with, he came out of with also and already closes the file).

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

2

I don’t like to interactively ask for filenames; I prefer the creation of scripts that receive parameters via line command. In that sense recommend the module fileinput:

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

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

This way the script works as 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()

  • I liked it! , and a good module I will use

Browser other questions tagged

You are not signed in. Login or sign up in order to post.