尝试在Python中写入csv文件时出现“在未引用的字段中看到的新行字符”错误

问题描述 投票:0回答:1

我创建了一个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)
python file csv newline read-write
1个回答
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,

希望这个答案可以帮助你^ _ ^欢呼

© www.soinside.com 2019 - 2024. All rights reserved.