如何更改行尾约定? [英] How to change end-of-line conventions?

查看:110
本文介绍了如何更改行尾约定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的任务.我需要创建一个文本文件,该文本文件在行尾使用unix LF约定.但是,当我尝试使用pandas .to_csv完成此操作时,最终得到CR LF.如果我呆在机器上并且所有内容都使用python,这将不是问题.但我不是.该代码将成为同事将使用的应用程序的一部分,并且文件将被发送给第三方以实现自动化.代码如下:

I have what I thought would be a simple task. I need to create a text file that has uses the unix LF convention at the end of a line. However, when I attempt to accomplish this using pandas .to_csv, I end up with CR LF. This wouldn't be a problem if I were staying on my machine and if I were using python for everything. But I am not. The code will be part of an app that a coworker will be using, and the file is being sent to a third party for automation. The code is as follows:

df.to_csv("filename.txt", sep = '\t',line_terminator = '\n')

这位于我的代码中间,但是当文件保存在目标文件夹中时,它总是切换回CR LF.我认为Windows与"有用有关" .我尝试使用没有运气的解决方案.我也没有运气找到用于Python的 dos2unix 类型的程序包.无论如何,我是否可以编写以'\ n'结尾的行并将其粘贴在Windows中(如果可能,请使用to_csv)?

This sits in the middle of my code, but it always switches back to CR LF when the files is saved in the target folder. I think it may be something to do with Windows being "helpful". I have tried to use this type of solution with no luck. I am also not having any luck finding a dos2unix type package for Python. Is there anyway that I can write lines that end in '\n' and have it stick in Windows (using to_csv if possible)?

我正在使用Python 2.7和Windows 7.

I am using Python 2.7 and Windows 7.

我了解notepad ++,但是我试图全部用Python编写,所以我的同事只需要单击一个按钮(完成后,我将使用Tkinter并将其冻结为.exe). .txt可以是Windows格式,但我将(am)将相同的信息写入.MAT和.ref文件.在这些文件中,它需要以'\ n'结尾,但是Windows仍然给我'\ r \ n'.

I know about notepad++, but I am trying to write this all in Python, so my coworker only has to click a button (I will be using Tkinter and freezing this to an .exe once I am finished). The .txt can be Windows formatted, but I will be (am) writing the same information to a .MAT and .ref file. In those files it needs the '\n' end of line, but Windows is still giving me '\r\n'.

推荐答案

to_csv默认以'w'模式打开文件,默认为文本模式.在Windows上,文本模式将\n转换为\r\n.而是以二进制模式打开文件,如果框架中包含非ASCII文本,则指定一种编码.

to_csv defaults to opening the file in 'w' mode which defaults to text mode. On Windows text mode translates \n to \r\n. Open the the file in binary mode instead, and specify an encoding if you have non-ASCII text in your frame.

df.to_csv('filename.txt',sep='\t',mode='wb',encoding='utf8')

这篇关于如何更改行尾约定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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