Python:防止添加换行符的文件输入 [英] Python: Prevent fileinput from adding newline characters
问题描述
我正在使用Python脚本查找并替换给定目录的文本文件中的某些字符串。我正在使用 fileinput
模块来简化查找和替换操作,即读取文件,替换文本并将其写回同一文件。
$ b
代码如下所示:
pre $ import $ file
def fixFile fileName):
#打开file inplace替换
作为fileinput.FileInput(fileName,inplace = 1)中的行:
line = line.replace(findStr,replaceStr )
print line#将文件放入文件
问题在于写入的文件:
- 在每行行之后插入一行空格。
- 每行结尾的-M字符。
如何防止这些额外的附件插入进入文件?
你的换行符来自打印功能
<
import sys
sys.st dout.write('some stuff')
您的换行符将会消失
I am using a Python script to find and replace certain strings in text files of a given directory. I am using the fileinput
module to ease the find-and-replace operation, i.e., the file is read, text replaced and written back to the same file.
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:
- One blank line inserted after every line.
- Ctrl-M character at the end of every line.
How do I prevent these extra appendages from getting inserted into the files?
Your newlines are coming from the print function
use:
import sys
sys.stdout.write ('some stuff')
and your line breaks will go away
这篇关于Python:防止添加换行符的文件输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!