“在Python中尝试写入csvfile时,在无引号字段中看到换行符”错误

2024-09-30 03:25:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个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)

Tags: 文件csvlogascontents模式open字符
1条回答
网友
1楼 · 发布于 2024-09-30 03:25:14

我建议使用回复sub(python)操作regex

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,

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

相关问题 更多 >

    热门问题