Not able to read rpt file using Python 3

1.8k Views Asked by At

I am trying to read a .rpt file using the python code:

>>> with open(r'C:\Users\lenovo-pc\Desktop\training2.rpt','r',encoding = 'utf-8', errors = 'replace') as d:
...     count = 0
...     for i in d.readlines():
...         count = count + 1
...         print(i+"\n")
...
...


u

i

d

|

e

x

p

i

d

|

n

a

m

e

|

d

o

m

a

i

n

And I am getting the following result as mentioned above. Kindly, let me know how I can read the .rpt file using python3.

1

There are 1 best solutions below

0
On

This is, indeed, strange behavior. While I can not easily reproduce the error without knowing the format of the .rpt file here are some hints what might go wrong. I assume it looks something like this:

uid|expid|name|domain
...

Which can be read and printed with the following code:

with open(r'C:\Users\lenovo-pc\Desktop\training2.rpt','r',encoding = 'utf-8', errors = 'replace') as rfile:
    count = 0
    for line in rfile:
        count += 1
        print(line.strip())  # this removes white spaces, line breaks etc.

However, the problem seems to be that you iterate over the string of the first line in your file instead of the lines in the file. That would produce the patter of you see, as the print() function adds a line break (in addition to the one you add manually). This leaves you with on character per line (followed by two line breaks).

>>> for i in "foo":
...     print(i+"\n")
f

o

o

Make sure you did not reuse variable names from earlier in the session and do not overwrite the file object.