'Program crashes during reading text file

def process_file(self):
        error_flag = 0
        line_count = 0
        log_file = self.file_name
        pure_name = log_file.strip()
        # print('Before opening file ',pure_name)
        logfile_in = open(pure_name, 'r')  # Read file

        lines = logfile_in.readlines()
        # print('After reading file enteries ', pure_name)

Error Message

Traceback (most recent call last):
  File "C:\Users\admin\PycharmProjects\BackupLogCheck\main.py", line 49, in <module>
    backupLogs.process_file()
  File "C:\Users\admin\PycharmProjects\BackupLogCheck\main.py", line 20, in process_file
    lines = logfile_in.readlines()
  File "C:\Users\admin\AppData\Local\Programs\Python\Python39\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 0x90 in position 350: character maps to <undefined>

Process finished with exit code 1

Line 49 is where I call above method. But I have traced that it crashes at reading the file. I have checked the file; it has just text in it. I don't know if there are some characters which it doesn't like on reading entries. I am running on Windows 10. I am new to Python, any suggestion how to find/correct the issue?



Solution 1:[1]

Try the file name in string format

logfile_in = open('pure_name', 'r')  # Read file
lines = logfile_in.readlines()

print(lines)

output

['test line one\n', 'test line two']

or

logfile_in = open('pure_name', 'r')  # Read file
lines = logfile_in.readlines()

for line in lines:
    print(line)

output

test line one

test line two

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 wjandrea