[英]with python, how can i convert a txt file on windows to a unix type?
often times, i forget to change the document type(?) to unix, instead of windows before loading to a linux environment.很多时候,在加载到 linux 环境之前,我忘记将文档类型(?)更改为 unix,而不是 windows。
when i run the file from there, i get:当我从那里运行文件时,我得到:
filename.sh: line 4: $'\r': command not found
is there a way to change the text file from python?有没有办法从 python 更改文本文件?
ideally, through a sub process on the command line or something that doesn't require me to open the file and add EOL stuff?理想情况下,通过命令行上的子进程或不需要我打开文件并添加 EOL 的东西?
otherwise, is there a way to build that into a return from the subprocess?否则,有没有办法将其构建为子流程的回报?
because if i do $?
因为如果我做$?
i get 0
after running a text that is not formatted correctly.运行格式不正确的文本后,我得到0
。
edit:编辑:
something weird is happening - i was originally testing this out in linux and was getting that 'error'.发生了一些奇怪的事情——我最初是在 linux 中测试它并得到那个“错误”。 when i run plink
on a the same file, it actually reads it like unix and runs it correctly...当我在同一个文件上运行plink
时,它实际上像 unix 一样读取它并正确运行它......
Yes, with the newline
parameter of open
.是的,使用open
的newline
参数。 By default open
uses universal newline when text mode is used, and converts all new line types (\r, \n, \r\n) to \n.默认情况下, open
在使用文本模式时使用通用换行符,并将所有新行类型(\r、\n、\r\n)转换为 \n。 Read the whole file in, then write it out again with a specified newline
:读入整个文件,然后用指定的newline
再次写出:
Example (overwrites original file!):示例(覆盖原始文件!):
import sys
with open(sys.argv[1]) as f: # default is 'rt' read text mode.
data = f.read()
with open(sys.argv[1], 'w', newline='\n') as f: # write with Unix new lines.
f.write(data)
Also, without newline
specified it will use the platform default, so on Windows it will write \r\n endings, and on Unix it will write \n endings if you leave the parameter out.此外,如果没有指定newline
,它将使用平台默认值,因此在 Windows 上它将写入 \r\n 结尾,而在 Unix 上,如果您不使用该参数,它将写入 \n 结尾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.