【问题标题】:txt to csv attempt. cannot understand the TypeError from retxt 到 csv 的尝试。无法理解来自 re 的 TypeError
【发布时间】:2020-12-16 09:04:07
【问题描述】:

我正在尝试将此文件 https://bpa.st/SNPQ 转换为 CSV 文件。我花了很长时间将这段代码放在一起,但我不明白为什么它会失败。

import re
f = open('PRM93052012100845','r')
text = f.readlines()
text = re.sub('^\n|\n$','',text)
for no,line in enumerate(text.splitlines()):
    print('"'+'","'.join([i.replace('"','\\"').strip() for i in re.split('(?<=^[0-9]{2})([0-9]{13}| {13})|  +',text.splitlines()[no].strip()) if i != None])+'"')

(比粘贴示例中的行多得多)

我得到以下输出:

Traceback (most recent call last):
  File "/home/ben/Documents/WDL Content/eCom Python/printtest.py", line 5, in <module>
    text = re.sub('^\n|\n$','',text)
  File "/usr/lib/python3.8/re.py", line 210, in sub
    return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or bytes-like object

我希望我可以说文件中有一些错误的数据,但是有一个 MS Office 宏可以完成相同的目标。我很想知道我做错了什么。

【问题讨论】:

  • f.readlines() 返回一个列表,请改用read()

标签: python csv python-re txt


【解决方案1】:

text = f.readlines() 为您提供列表,因此您不能将它与 re.sub 一起使用,因为它期望 stringbytes。将其替换为text = f.read()

【讨论】:

  • 谢谢,这似乎已经解决了!
  • 很高兴它有帮助:),如果解决了您的问题,您可以将其标记为已接受
猜你喜欢
  • 2018-04-07
  • 2017-09-05
  • 2017-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-17
  • 2021-10-10
  • 2016-12-14
相关资源
最近更新 更多