Home > Enterprise >  Can't read the number of lines in a file using Python
Can't read the number of lines in a file using Python

Time:08-16

I've written a Python code in which I am trying to read the number of lines in the file and it is not executing i.e it is showing some errors.

Code:

fhand=open('programms.txt')
count=0
for line in fhand:
    count=count   1
print('Line Count: ',count)

Output:

Traceback (most recent call last):
  File "F:/PythonP/files.py", line 3, in <module>
    for line in fhand:
  File "C:\Users\NC\AppData\Local\Programs\Python\Python310\lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 299: character maps to <undefined>

CodePudding user response:

It may be an encoding problem, try specifying it when opening the file.

fhand=open('programms.txt', encoding="utf8")
count=0
for line in fhand:
    count=count   1
print('Line Count: ',count)

CodePudding user response:

I See that you're facing an error UnicodeDecodeError which means that the content of your file contains characters other than ASCII You can read the file in other ways, for example if your file is formatted in utf-8 you'll need an external python module called codecs to be able to read these characters

import codecs

with codecs.open('programms.txt', 'utf-8') as file:
   lines = file.readlines()
   total_lines = len(lines)

print(total_lines)

CodePudding user response:

with open(r"E:\demos\files\read_demo.txt", 'r') as fp:
    for count, line in enumerate(fp):
        pass
print('Total Lines', count   1)

CodePudding user response:

You can get a list containing the lines with fhand.readlines(), then get the number of lines with len():

fhand = open('programms.txt', "r")
lines = fhand.readlines()
line_count = len(lines)
print("Line Count: ", line_count)
  • Related