How to verify the existence of a file and the number of lines written in Python?

Asked

Viewed 1,153 times

0

How best to check whether the file is existing and the number of lines inside the file.

  • 1

    What you’ve tried and why it didn’t work?

  • I only used Try and except, but I don’t know if it’s the best one to do. 'Cause I’m doing a critical program, so I should take the utmost care to avoid failures.

1 answer

2


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

To count the lines, just discover 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 :(')
  • An error occurs in the path, and using Len returns "None" even if the file is written.

  • Which error? This path is a path on my computer. You may have to modify it to find your file. I can’t test for Windows at the moment, but it works here.

  • Yes I modified for my path on linux, but it didn’t work.

  • What is your path?

  • /home/Filipe/Proj/data/config.dat

  • Can be done with the module os easily: https://stackoverflow.com/questions/2259382/pythonic-way-to-check-if-a-file-exists

  • Strange, I don’t know why it wouldn’t work. Can you give cat, wc -l /home/filipe/Proj/data/config.dat, etc? You can try with the os, as in the above suggestion.

Show 2 more comments

Browser other questions tagged

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