2017-03-03 8 views
0

私は2つのpythonスクリプトを持っています.1つはbase64にファイルをエンコードします(これは正常に動作します)。Pythonベース64のデコード - 改行を開始するのではなく nをプリントします。

import base64 
read_file = input('Name of file to read: ') 
write_file = input('Name of file to write to: ') 
image = open("%s"% read_file,'rb') 
image_read = image.read() 
image_64_encode = base64.encodestring(image_read) 

raw_file = open("rawfile.txt","w") 
raw_file.write("%s"% image_64_encode) #Write the base64 to a seperate text file 
raw_file.close() 

image_64_decode = base64.decodestring(image_64_encode) 
image_result = open('%s'% write_file,'wb') 
image_result.write(image_64_decode) 
image_result.close() 
image.close() 

上記のスクリプトは正常に実行され、新しいファイル(デコード済み)とエンコードされた文字列として表示される別のrawfile.txtを正常に書き込みます。したがって、この半分のプロセスは問題ありません。

私が生ファイルの内容を印刷することができる、rawfile.txt復号する第Pythonスクリプトを持っているのではなく、所望の

より生ファイルは、新しい行を有し、パイソンプリント

somerawfiletext\nmorerawfiletext 

somerawfiletext 
morerawfiletext 

私はbase64のパディングエラーが発生するため、解読できません。

二Pythonスクリプトは:

import base64 
rawfile = open("rawfile.txt",'r') 
for line in rawfile: 
    print(line.rstrip()) 
decoded = base64.decodestring(rawfile) 
print(decoded) 

答えて

0

代わりencodestringb64encodeを使用する最初のスクリプトを変更することができます。これには改行はまったく含まれていないので、手動で追加することができます。次に、改行文字を使用して読み込み可能なファイルが作成され、デコードされます。だから私はあなたのファイルは次のようになりますと仮定しています:

FILE1.TXT:

string1 
string2 
string3 

を今、あなたは単純なループに沿って、その行をエンコードすることができ、リストに固執:

data = [] 
with open('file1.txt') as f: 
    for lines in f: 
     data.append(base64.b64encode(lines)) 

今ファイルにそのリストを書く:今すぐ

with open('encoded_file.txt', 'w') as f: 
    for vals in data: 
     f.write(vals + '\n') 

そのファイル、デコードおよび印刷物で読むために:

with open('encoded_file.txt') as f: 
    for vals in f.readlines(): 
     print(base64.decodestring(vals)) 

最初のループ、使用する場所になるあなたはまた、別のリスト内生ヴァルスを保存し、同じ方法を使用してファイルに保存することができます:

raw_data = [] 
data_to_encode = [] 
with open('file1.txt') as f: 
for lines in f: 
    data_to_encode.append(base64.b64encode(lines)) 
    raw_data.append(lines) 

次にあなたがリストを持っていますあなたが望むように使用できる生データとコード化データの

+0

ありがとうございました。帰ってきたら、これを試してみます。 :) –

関連する問題