[英]Replace Carriage Return (CR) and Carriage Return and Line Feed (CRLF) python
[英]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
模块不支持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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.