【问题标题】:'new-line character seen in unquoted field'-error when trying to write to a csv-file in Python'在未引用的字段中看到换行符'-尝试在 Python 中写入 csv 文件时出错
【发布时间】:2019-03-01 10:17:39
【问题描述】:

我创建了一个 Python 脚本,我想在其中读取文件、对其进行预处理并将其写入为 CSV 文件。

但是,当我尝试在每个“)”字符上创建一个新行时,我遇到一个问题:“在未引用的字段中看到换行符 - 你需要以通用换行模式打开文件吗? "我已经看到一些建议尝试同时使用 'rU' 和 'rb' 作为模式参数,但我尝试了这个但没有运气。还有其他建议吗?

这是我的脚本的样子:

with open('testlogs', 'r', newline='') as log_file, open('output.csv', 'w') as csv_file:
contents = log_file.read()  
dataPoints = re.findall('\[(.*?)\]', contents)
parsedLog = [item.replace(' ', '').replace('(', '').replace(')', '\n') for item in dataPoints]

reader = csv.reader(parsedLog)
writer = csv.writer(csv_file)
writer.writerows(reader)

【问题讨论】:

  • 错误信息意味着你的正则表达式匹配了一个行边界。
  • 试过你的代码,但我没有遇到这个问题 - 你能提供输入文件吗?另外,来源是什么,是 Excel 编写的 CSV 文件吗?在 Windows 上?

标签: python file csv newline read-write


【解决方案1】:

我建议使用 re.sub (python) 来操作正则表达式

import fileinput
import re

logfile="error.log"
outfile="clean.csv"

with open("error.log") as f:
   newText = f.read()
   newText = re.sub(r" ", "", newText)
   newText = re.sub(r"(", "", newText)
   newText = re.sub(r")", "\n", newText)    

   with open("clean.csv", "w") as f:
      f.write(newText)

如果你想在第一行.csv文件中添加一些参数,只需在上面的源代码末尾添加:

for line in fileinput.input(files=['clean.csv'], inplace=True):
    if fileinput.isfirstline():
        print 'parameter1,parameter2,parameter3, .... '
    print line,

希望这个答案能帮到你^_^干杯

【讨论】:

  • 我试过这个,但它给了我另一个错误:“re.error: missing ), unterminated subpattern at position 0” on line with "newText = re.sub(r"(", "" , newText)"。
  • 试试这个newText = re.sub(r"\(", "", newText)和newText = re.sub(r"\)", "\n", newText)
  • 谢谢,现在可以使用了!是否也可以使用 findall 来保留与正则表达式匹配的所有数据,就像我之前对这一行所做的那样: dataPoints = re.findall('[(.*?)]', contents) ?
猜你喜欢
  • 2018-01-26
  • 2013-06-23
  • 2013-01-03
  • 2013-04-30
  • 2013-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多