(python3)如何将二进制文件作为文本传递而不保存firs

2024-10-03 06:28:11 发布

您现在位置:Python中文网/ 问答频道 /正文

或者,也许是一个更好的标题:当将二进制文件传递到文本模式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在我的代码里。(底层库中可能有,我还没有检查过。)

我做错什么了?在


Tags: 文件文本windowsdefaswith二进制模式
1条回答
网友
1楼 · 发布于 2024-10-03 06:28:11

Python » Documentation : open

open(file, mode='r', buffering=-1, encoding=None, errors=None, 
           newline=None, closefd=True, opener=None)  

默认值newline=None如果换行符是''或{},则不进行转换。
如果有任何不同,请尝试以下操作:

#change
    open(outfile, encoding='utf-8-sig', mode='w') as g:
#with
    open(outfile, encoding='utf-8-sig', mode='w', newline='') as g:

Question: ... there is no os.linesep in my code.


Python » Documentation : open
When writing output to the stream, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '' or '\n', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string.

相关问题 更多 >