Python:防止文件输入添加换行符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/657186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:34:01  来源:igfitidea点击:

Python: Prevent fileinput from adding newline characters

pythonfile-io

提问by Ashwin Nanjappa

I am using a Python script to find and replacecertain strings in text files of a given directory. I am using the fileinputmodule to ease the find-and-replace operation, i.e., the file is read, text replaced and written back to the same file.

我正在使用 Python 脚本来查找和替换给定目录的文本文件中的某些字符串。我正在使用该fileinput模块来简化查找和替换操作,即读取文件、替换文本并写回同一个文件。

The code looks as follows:

代码如下所示:

import fileinput
def fixFile(fileName):
    # Open file for in-place replace
    for line in fileinput.FileInput(fileName, inplace=1):
        line = line.replace("findStr", "replaceStr")
        print line  # Put back line into file

The problem is that the written files have:

问题是写入的文件有:

  1. One blank line inserted after everyline.
  2. Ctrl-M character at the end of everyline.
  1. 行后插入一个空行。
  2. 行末尾的 Ctrl-M 字符。

How do I prevent these extra appendages from getting inserted into the files?

如何防止这些额外的附件被插入到文件中?

回答by jottos

Your newlines are coming from the print function

您的换行符来自打印功能

use:

利用:

import sys

sys.stdout.write ('some stuff')

and your line breaks will go away

你的换行符会消失

回答by Eugene Morozov

Use

利用

print line,

or

或者

file.write(line)

to fix extra newlines.

修复额外的换行符。

As of [Ctrl]-[M] - that is probably caused by input files in DOS encoding.

从 [Ctrl]-[M] 开始 - 这可能是由 DOS 编码的输入文件引起的。

回答by kwarnke

Instead of this:

取而代之的是:

print line  # Put back line into file

use this:

用这个:

print line,  # Put back line into file

回答by kmote

Change the first line in your for loop to:

将 for 循环中的第一行更改为:

line = line.rstrip().replace("findStr", "replaceStr")

line = line.rstrip().replace("findStr", "replaceStr")

回答by Senthil Murugan

Due to every iteration print statement ends with newline, you are getting blank line between lines.

由于每个迭代打印语句都以换行符结尾,因此在行之间会出现空行。

To overcome this problem, you can use strip along with print.

为了克服这个问题,您可以将条带与打印一起使用。

import fileinput
def fixFile(fileName):
  for line in fileinput.FileInput(fileName, inplace=1):
    line = line.replace("findStr", "replaceStr")
    print line.strip()

Now, you can see blank lines are striped.

现在,您可以看到空白行被条纹化。

回答by Antoine

For the update on Python 4.3, you can just use:

对于 Python 4.3 的更新,您可以使用:

print(line, end = '')

to avoid the insertion of a new line.

以避免插入新行。