在Python中添加一个额外的回车的CSV [英] CSV in Python adding an extra carriage return

查看:176
本文介绍了在Python中添加一个额外的回车的CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在运行Windows XP的Python 2.7中:

  import csv 
outfile = file csv','w')
writer = csv.writer(outfile,delimiter =',',quoting = csv.QUOTE_MINIMAL)
writer.writerow(['hi','dude'])
writer.writerow(['hi2','dude2'])
outfile.close()

它会生成一个文件test.csv,每行都有一个额外的\r,例如:



test.csv



  hi,dude\r\r\\\
hi2,dude2\r\r\\\



而不是预期:

  hi,dude\r\ nhi2,dude2 \r\\\

为什么会发生

$ p

解决方案

在Windows上,总是以二进制模式打开文件(rb



CSV实际上是一种二进制格式,其中包含\r\\ \\ n分隔记录。如果该分隔符是以文本模式编写的,则Python运行时将\\\
替换为\r\\\
,因此在文件中观察到\r\r\\\

请参阅此前回答


In Python 2.7 running on Windows XP pro:

import csv
outfile = file('test.csv', 'w')
writer = csv.writer(outfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
writer.writerow(['hi','dude'])
writer.writerow(['hi2','dude2'])
outfile.close()

It generates a file, test.csv, with an extra \r at each row, like so:

test.csv

hi,dude\r\r\nhi2,dude2\r\r\n

instead of the expected:

hi,dude\r\nhi2,dude2\r\n

Why is this happening, or is this actually the desired behavior?

解决方案

On Windows, always open your files in binary mode ("rb" or "wb") before passing them to csv.reader or csv.writer.

CSV is really a binary format, with "\r\n" separating records. If that separator is written in text mode, the Python runtime replaces the "\n" with "\r\n" hence the "\r\r\n" that you observed in your file.

See this previous answer.

这篇关于在Python中添加一个额外的回车的CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆