简体   繁体   English

用空格替换换行(LF),但不影响回车(CR)

[英]Replace line feed (LF) with space but not affect carriage return (CR)

Is there a way to remove line feeds (LF) and replace with space and not affect the carriage returns (CR)? 有没有办法删除换行符(LF)并用空格代替并且不影响回车(CR)?

I've tried the below but it also removes the carriage returns: 我已经尝试了下面的方法,但是它也删除了回车符:

import fileinput
import sys

def replaceAll(file,searchExp,replaceExp):
    for line in fileinput.input(file, inplace=1):
        if searchExp in line:
            line = line.replace(searchExp,replaceExp)
        sys.stdout.write(line)

replaceAll("hold1.csv","\n","\s")

The input text would be something like this with | 输入文本将是类似|的 as a separator: 作为分隔符:

field1 | field2| field3 some textLF

more textLF

more text|field4 | field5 CR

Which I would like to see in the format of: 我想以以下格式看到:

field1 | field2| field3 some text more text more text|field4 | field5 CR

It is not your replacing code removes the carriage returns. 不是您的替换代码会删除回车符。 Python, by default, normalises line endings when opening files in text mode; 默认情况下,Python在以文本模式打开文件时会规范行尾 a feature called universal newlines . 一种称为通用换行符的功能。 See the open() function documentation : 请参阅open()函数文档

When reading input from the stream, if newline is None, universal newlines mode is enabled. 从流中读取输入时,如果newline为None,则启用通用换行符模式。 Lines in the input can end in '\\n', '\\r', or '\\r\\n', and these are translated into '\\n' before being returned to the caller. 输入中的行可以以'\\ n','\\ r'或'\\ r \\ n'结尾,在返回给调用者之前,这些行会转换为'\\ n'。 If it is '', universal newlines mode is enabled, but line endings are returned to the caller untranslated. 如果为”,则启用通用换行模式,但行结尾不翻译就返回给呼叫者。

You want to use the newline='' mode. 您要使用newline=''模式。 Unfortunately, the fileinput module doesn't support combining inline and openhook , so you'll have to create your own backups to re-write the files: 不幸的是, fileinput模块不支持inlineopenhook组合 ,因此您必须创建自己的备份来重写文件:

import os

def replaceAll(file, searchExp, replaceExp):
    backup = file + '.bak'
    os.rename(file,  backup)
    with open(backup, 'r', newline='') as source, open(file, 'w', newline='') as dest:
        for line in source:
            if searchExp in line:
                line = line.replace(searchExp, replaceExp)
            dest.write(line)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM