是否可以删除换行符(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
答案 0 :(得分:1)
不是您的替换代码会删除回车符。在默认情况下,Python在以文本模式打开文件时会标准化行结尾;名为universal newlines的功能。参见open()
function documentation:
从流中读取输入时,如果
newline
为None,则启用通用换行模式。输入中的行可以以'\ n','\ r'或'\ r \ n'结尾,在返回给调用者之前,这些行会转换为'\ n'。如果为“”,则启用通用换行模式,但行结尾不翻译就返回给呼叫者。
您要使用newline=''
模式。不幸的是,fileinput
模块不支持将inline
和openhook
结合使用,因此您必须创建自己的备份来重写文件:
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)