【问题标题】:python fileinput line endingspython文件输入行结尾
【发布时间】:2014-11-23 19:58:55
【问题描述】:

我有一些 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 的文件中。

问题在于 out_filename 中的行结尾。 它们应该是 \r\n 但我插入的块是 \r\r\n。

将打印语句更改为:

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

print content.replace('\r\r','\r')  # no change

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

我该如何解决这个问题?

【问题讨论】:

  • 您是否尝试过改用rstrip('\r\n')
  • 刚刚尝试打印 content.rstrip('\r\n') 并没有改变

标签: python newline


【解决方案1】:

我可以通过以下方式“解决”这个问题:

content = content.replace('\r\n', '\n')

将换行符转换为 unix 样式,这样当内部魔法再次转换它时,它最终是正确的。

虽然这不是正确/最好/pythonic的方式....

【讨论】:

    【解决方案2】:

    CRLF = 回车换行。

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

    https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files

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

    如果在字符串前面加上 r 前缀 open the file as raw,这会阻止输出中出现额外的 \r 吗?

    【讨论】:

    • for line in fileinput.input(filename, inplace=1, mode='rb'): 奇怪的是让事情变得更糟。不仅 \r\r\n 仍然存在,而且文件的其余部分现在也有它们(不仅仅是插入的部分)
    猜你喜欢
    • 2015-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 2013-01-11
    • 1970-01-01
    相关资源
    最近更新 更多