【发布时间】: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