Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
(Python 3)如何以文本形式传递二进制文件而不首先保存_Python_Python 3.6 - Fatal编程技术网

(Python 3)如何以文本形式传递二进制文件而不首先保存

(Python 3)如何以文本形式传递二进制文件而不首先保存,python,python-3.6,Python,Python 3.6,或者,也许是一个更好的标题:如何在将二进制文件传递到文本模式write子句时避免不必要的额外回车 Python 3.6,Windows。输入文件首先需要进行二进制搜索/替换,然后是正则表达式搜索/替换 我首先以二进制模式打开输入文件,完成工作,然后以二进制模式将其保存在临时文件中。然后我以文本模式打开它,执行regex搜索/替换,并以文本模式保存它(名称类似于输入文件) 它能用,但很难看。我宁愿将输出作为文件传递,如下所示: def fixbin(infile): with open(

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

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

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

它能用,但很难看。我宁愿将输出作为文件传递,如下所示:

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)会得到不需要的额外回车。症状已经描述,但原因不同:我没有使用os.linesep,换句话说,我的代码中没有os.linesep。(底层库中可能有,我还没有检查。)

我做错了什么

Python»文档

默认值
换行符=无
如果换行符是
'
'\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»文档
将输出写入流时,如果换行符为None,则写入的任何“\n”字符都将转换为系统默认的行分隔符os.linesep。如果换行符为“”或“\n”,则不会进行转换。如果换行符是任何其他合法值,则写入的任何'\n'字符都将转换为给定字符串

“我没有使用os.linesep”,您怎么会对舒尔这么说呢?请解释。
open(file, mode='r', buffering=-1, encoding=None, errors=None, 
           newline=None, closefd=True, opener=None)  
#change
    open(outfile, encoding='utf-8-sig', mode='w') as g:
#with
    open(outfile, encoding='utf-8-sig', mode='w', newline='') as g: