How to check the existence of a file and the amount of lines written in Python?

0

What is the best way to check if the file exists and the number of lines within the file.

    
asked by anonymous 23.01.2018 / 13:11

1 answer

2

You can use is_file of pathlib.Path to find out if the file exists.

To count the lines, just find the len of reading the file:

from pathlib import Path

caminho = Path('./arquivo.txt')

if caminho.is_file():
    print('Arquivo existe!')
    with open(caminho, 'r') as f:
        n_linhas = len(f.readlines())
    print('Ele tem {} linhas.'.format(n_linhas))
else:
    print('Arquivo inexistente :(')
    
23.01.2018 / 13:24