【问题标题】:Not able to read rpt file using Python 3无法使用 Python 3 读取 rpt 文件
【发布时间】:2017-07-20 09:45:54
【问题描述】:

我正在尝试使用 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 文件。

【问题讨论】:

  • 你的意思是for i in d.readlines()
  • @ason​​gtoruin 是的
  • 这能解决您的问题吗??
  • 不......它没有。我也试过了
  • 你能发布你使用d.readlines()而不是d.readline()时得到的结果吗?

标签: python python-3.x rpt


【解决方案1】:

这确实是一种奇怪的行为。虽然我无法在不知道 .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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-13
    • 1970-01-01
    • 2016-12-03
    • 2016-04-06
    • 2019-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多