0

我正在尝试使用 python 代码读取 .rpt 文件:

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

如上所述,我得到了以下结果。请让我知道如何使用 python3 读取 .rpt 文件。

4

1 回答 1

0

这确实是一种奇怪的行为。虽然我无法在不知道 .rpt 文件格式的情况下轻松重现错误,但这里有一些可能出错的提示。我认为它看起来像这样:

uid|expid|name|domain
...

可以使用以下代码读取和打印:

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.

但是,问题似乎是您遍历文件中第一行的字符串而不是文件中的行。这会产生你看到的模式,因为该print()函数添加了一个换行符(除了你手动添加的那个)。这使您每行都有一个字符(后跟两个换行符)。

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

o

o

确保您没有重用会话早期的变量名称,并且不要覆盖文件对象。

于 2017-07-20T13:12:26.013 回答