Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/349.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.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中与dictwriter一起使用时正确删除回车符(换行符=';';没有帮助)_Python_Json_Csv - Fatal编程技术网

如何在python中与dictwriter一起使用时正确删除回车符(换行符=';';没有帮助)

如何在python中与dictwriter一起使用时正确删除回车符(换行符=';';没有帮助),python,json,csv,Python,Json,Csv,我有一个简单的pythono代码,它解析json文件并将其作为字典返回。我必须将其写入CSV文件,但只能使用LF作为行终止符。但是,即使使用换行符='',回车符也会出现。当我收到此错误时,wb模式不是一个选项 返回self.writer.writerow(self.\u dict\u to\u list(rowdict)) TypeError:需要类似字节的对象,而不是“str” 我的CSV编写代码: with open(statsFilePath,'w+', newline='', encod

我有一个简单的pythono代码,它解析json文件并将其作为字典返回。我必须将其写入CSV文件,但只能使用LF作为行终止符。但是,即使使用换行符='',回车符也会出现。当我收到此错误时,wb模式不是一个选项

返回self.writer.writerow(self.\u dict\u to\u list(rowdict)) TypeError:需要类似字节的对象,而不是“str”

我的CSV编写代码:

with open(statsFilePath,'w+', newline='', encoding='utf8') as f:
  writer = csv.DictWriter(f, header , delimiter = '|')
  for row in result:
    writer.writerow(row)
这是我在记事本中看到的屏幕截图++

更新,已解决

DictWriter使用默认的行终止符。将代码更改为此,解决了以下问题:

with open(statsFilePath,'w+', newline='', encoding='utf8') as f:
    writer = csv.DictWriter(f, header , delimiter = '|', lineterminator="\n")
    for row in result:
        writer.writerow(row)  
试试这个:

with open(statsFilePath,'w+', newline='\n', encoding='utf8') as f:

请记住,
LF
可能不是您想要的。您正在寻找
CR
作为行分隔符(UNIX的默认值)。

csv
方言决定使用哪一行终止符,并将其替换

定义写入程序时,需要指定
lineterminator

writer = csv.DictWriter(f, header , delimiter = '|', lineterminator='\n')

不幸的是,也尝试了\n并得到了相同的结果请注意,
\n
的值并不意味着输出中将只使用LF。它只相当于空字符串
'
,表示不执行翻译。这意味着,如果您写入的字符串包含
\r\n
,则它将写入
\r\n
,而不是
\n
。默认情况下,
DictWriter
可能使用
os.linesep
,这将导致OP描述的内容。顺便说一句:linux和MacOS都不使用CR。他们都使用LF,即
\n
你说得对,DictWriter使用了默认linesep,刚刚发现我可以使用“lineterminator”更改它。感谢You@AlexShangin我也发现了这一点,并花时间发布了答案。为什么你接受了一个在这种情况下没有用的答案?你的答案是对的,但在我找到它一分钟后就贴出来了,谢谢你!