2017-04-20 6 views
2

または、おそらくより良いタイトル:バイナリファイルをテキストモードの書き込み句に渡すときに不要な余分なキャリッジリターンを回避する方法。(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はありません。 (下の図書館には私がチェックしていないかもしれません)

私は間違っていますか?

+0

どのようにShure about _「os.linesepを使用していませんか」_、説明してください。 – stovfl

+0

@stovl編集してご覧ください。 – RolfBly

答えて

1

のPython»ドキュメントopen
オープン(ファイル、モード= 'R'、バッファリング= -1、エンコーディング=なし、エラー=なし、改行=なし、closefd =真、オープナー=なし)

デフォルト: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»ドキュメントは:改行がNone場合open
ストリームに出力を書き込み、任意のは 『\ n』が書かれた文字は、システムのデフォルトの行区切り、os.linesepに翻訳されています。改行が ''または '\ n'の場合、翻訳は行われません。改行が他の有効な値のいずれかである場合、書き込まれた '\ n'文字は指定された文字列に変換されます。

関連する問題