または、おそらくより良いタイトル:バイナリファイルをテキストモードの書き込み句に渡すときに不要な余分なキャリッジリターンを回避する方法。(Python 3)バイナリファイルを最初に保存せずにテキストとして渡す方法
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はありません。 (下の図書館には私がチェックしていないかもしれません)
私は間違っていますか?
どのようにShure about _「os.linesepを使用していませんか」_、説明してください。 – stovfl
@stovl編集してご覧ください。 – RolfBly