Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
';在未加引号的字段中看到新行字符'-尝试在Python中写入csv文件时出错_Python_File_Csv_Newline_Read Write - Fatal编程技术网

';在未加引号的字段中看到新行字符'-尝试在Python中写入csv文件时出错

';在未加引号的字段中看到新行字符'-尝试在Python中写入csv文件时出错,python,file,csv,newline,read-write,Python,File,Csv,Newline,Read Write,我创建了一个Python脚本,我想在其中读取一个文件,对其进行预处理并将其作为CSV文件写入 然而,当我尝试在每个“)”-字符上创建新行时,我遇到了一个问题:“在不带引号的字段中看到新行字符-您需要以通用换行模式打开文件吗?”我看到一些建议尝试使用“rU”和“rb”作为模式参数,我尝试了这一点,但运气不佳。还有其他建议吗 这就是我的脚本的样子: with open('testlogs', 'r', newline='') as log_file, open('output.csv', 'w')

我创建了一个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)
我建议使用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)
如果要在first line.csv文件中添加一些参数,只需在上面的源代码末尾添加它:

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

希望此答案能帮助您^ ^ ^干杯

错误消息表示您的正则表达式跨行边界匹配。尝试编写代码,但我没有遇到此问题-您能提供输入文件吗?还有,CSV的来源是什么,是由Excel编写的吗?在Windows上?我尝试了这一点,但它给了我另一个错误:“re.error:missing”,在“newText=re.sub(r)(“,”,newText)”行的位置0处未终止的子模式。请尝试此
newText=re.sub(r“\(“,”,newText)
newText=re.sub(r“\”,“\n”,newText)
谢谢,它现在可以工作了!是否可以像我以前使用这行代码一样使用findall来保存与正则表达式匹配的所有数据:dataPoints=re.findall(“[(.*)”,contents)?