Search code examples
pythonfile-handling

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


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>

Solution

  • 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)