或者,也许是一个更好的标题:当将二进制文件传递到文本模式write子句时,如何避免不必要的额外回车。在
Python3.6,Windows。输入文件需要先进行二进制搜索/替换,然后再进行正则表达式搜索/替换。在
我首先在二进制模式下打开输入文件,完成工作,然后以二进制模式将其保存在一个临时文件中。然后我在文本模式下打开它,执行regex搜索/替换,并以文本模式保存它(使用类似于输入文件的名称)。在
def fixbin(infile):
with open(infile, 'rb') as f:
file = f.read()
# a few bytearray operations here, then:
with open('bin.tmp', 'wb') as f:
f.write(file)
def fix4801(fname, ext):
outfile = '{}_OK{}'.format(fname, ext)
with open('bin.tmp', encoding='utf-8-sig', mode='r') as f, \
open(outfile, encoding='utf-8-sig', mode='w') as g:
infile = f.read()
x = re.sub(r'(\n4801.+\n)4801', r'\1 ', infile)
g.write(y)
infile, fname, ext = get_infile() # function get_infile not shown for brevity
fixbin(infile)
fix4801(fname, ext)
它有用,但很难看。我宁愿将输出作为文件传递,如下所示:
^{pr2}$但是输出文件(Windows)会得到一个多余的回车符。症状描述为here,但原因不同:我没有使用os.linesep
,换句话说,没有操作系统linesep在我的代码里。(底层库中可能有,我还没有检查过。)
我做错什么了?在
默认值:},则不进行转换。
newline=None
,如果换行符是''
或{如果有任何不同,请尝试以下操作:
相关问题 更多 >
编程相关推荐