Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2008/2.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文件输入行结尾_Python_Newline - Fatal编程技术网

python文件输入行结尾

python文件输入行结尾,python,newline,Python,Newline,我有一些python代码,它的行尾都错了: command = 'svn cat -r {} "{}{}"'.format(svn_revision, svn_repo, svn_filename) content = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE).stdout.read() written = False for line in fileinput.input(out_filename, inpla

我有一些python代码,它的行尾都错了:

command = 'svn cat -r {} "{}{}"'.format(svn_revision, svn_repo, svn_filename)
content = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE).stdout.read()

written = False
for line in fileinput.input(out_filename, inplace=1):
        if line.startswith("INPUT_TAG") and not written:
            print content
            written = True
        print line,
这将获取名为svn_filename的文件副本,并将内容插入文件中“INPUT_TAG”位置名为out_filename的另一个文件中

问题是文件名中的行尾。 它们应该是\r\n,但我插入的块是\r\n

将打印语句更改为:

print content,  # just removes the newlines after the content block

没有效果。额外的回车在内容离开我的代码后插入。似乎有什么东西决定了,因为我在windows上,所以它应该将所有\n转换为\r\n


我怎样才能避开这个问题呢?

CRLF=回车换行

Windows上的Python区分了文本文件和二进制文件; 文本文件中的行尾字符将自动更改 在读取或写入数据时,会稍微改变

您可以输出为二进制文件而不是文本文件吗

如果在字符串前面加上“r to”,这是否会防止输出中出现额外的\r?

我可以通过执行以下操作“解决”此问题:

content = content.replace('\r\n', '\n')
将换行符转换为unix样式,这样当内部魔术再次转换它时,它就正确了


但这不可能是正确的/最好的/蟒蛇式的方式

您尝试过使用
rstrip('\r\n')
吗?只是尝试了打印content.rstrip('\r\n'),并且没有更改fileinput.input中的行(filename,inplace=1,mode='rb'):奇怪的是,这会让事情变得更糟。不仅\r\r\n仍然存在,而且文件的其余部分也有它们(不仅仅是插入的部分)
content = content.replace('\r\n', '\n')