【问题标题】:(Python 3) How to pass binary file as text without saving first(Python 3)如何将二进制文件作为文本传递而不先保存
【发布时间】:2017-09-17 15:28:19
【问题描述】:

或者,也许是一个更好的标题:如何在将二进制文件传递给文本模式写入子句时避免不必要的额外回车。

Python 3.6,Windows。输入文件需要首先进行二进制搜索/替换,然后是正则表达式搜索/替换。

我首先以二进制模式打开输入文件,完成工作,然后以二进制模式将其保存在临时文件中。然后我以文本模式打开它,进行正则表达式搜索/替换,并将其保存为文本模式(名称类似于输入文件的名称)。

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)

它有效,但它很丑。我宁愿将输出作为文件传递,如下所示:

def fixbin(infile): 
    with open(infile, 'rb') as f:
        file = f.read()
    # a few bytearray operations here, and then
    return file.decode('utf-8')

def fix4801(infile): 
    x = re.sub(r'(\n4801.+\n)4801', r'\1    ', infile)
    return x

...
temp = fixbin(infile)
result = fix4801(temp)

outfile = '{}_OK{}'.format(fname, ext)
with open(outfile, encoding='utf-8-sig', mode='w') as g:
    g.write(result)

但随后输出文件 (Windows) 会得到一个不需要的额外回车符。症状描述为here,但原因不同:我没有使用os.linesep,换句话说,我的代码中没有os.linesep。 (可能在底层库里,我没查过。)

我做错了什么?

【问题讨论】:

  • 你怎么会是舒尔关于“我没有使用os.linesep。”,请解释一下。

标签: python python-3.6


【解决方案1】:

Python » 文档open

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

默认newline=None如果换行符是'''\n',则不进行翻译。
如果有任何不同,请尝试以下操作:

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

问题:...我的代码中没有 os.linesep。


Python » 文档open
将输出写入流时,如果换行符为 None,则写入的任何 '\n' 字符都将转换为系统默认行分隔符 os.linesep。如果换行符是 '' 或 '\n',则不进行翻译。如果换行符是任何其他合法值,则写入的任何 '\n' 字符都将转换为给定的字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-24
    • 2015-06-14
    • 2016-02-21
    • 2015-12-31
    • 1970-01-01
    • 1970-01-01
    • 2016-07-12
    • 2011-11-07
    相关资源
    最近更新 更多