0
How best to check whether the file is existing and the number of lines inside the file.
0
How best to check whether the file is existing and the number of lines inside the file.
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.
Browser other questions tagged python python-3.x
You are not signed in. Login or sign up in order to post.
What you’ve tried and why it didn’t work?
– Pedro von Hertwig Batista
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.
– HelloWorld