What is the best way to check if the file exists and the number of lines within the file.
What is the best way to check if the file exists and the number of lines within the file.
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 :(')