簡體   English   中英

用空格替換換行(LF),但不影響回車(CR)

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

有沒有辦法刪除換行符(LF)並用空格代替並且不影響回車(CR)?

我已經嘗試了下面的方法,但是它也刪除了回車符:

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")

輸入文本將是類似|的 作為分隔符:

field1 | field2| field3 some textLF

more textLF

more text|field4 | field5 CR

我想以以下格式看到:

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

不是您的替換代碼會刪除回車符。 默認情況下,Python在以文本模式打開文件時會規范行尾 一種稱為通用換行符的功能。 請參閱open()函數文檔

從流中讀取輸入時,如果newline為None,則啟用通用換行符模式。 輸入中的行可以以'\\ n','\\ r'或'\\ r \\ n'結尾,在返回給調用者之前,這些行會轉換為'\\ n'。 如果為”,則啟用通用換行模式,但行結尾不翻譯就返回給呼叫者。

您要使用newline=''模式。 不幸的是, 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