我需要打开一个文件,读取一行,哈希,然后保存到另一个文件。我应该在脚本开头打开两个文本文件,还是每次保存/读取时都应该打开每个文本文件?我对这一切都很陌生,我使用python for android for sl4a。到目前为止,这是我的代码:
import android
import hashlib
import time
name = 0
droid = android.Android()
name = raw_input("Enter a password to hash: ")
hash_object = hashlib.md5 (name)
print(hash_object.hexdigest())
time.sleep(2)
print name
f = open('name.txt', 'w',)
f.write(hash_object.hexdigest())
f.close()
答案 0 :(得分:6)
如果您想从文件name.txt
中读取并写入另一个文件:
with open('name.txt', 'r') as f, open('out.txt', 'w') as f1:
line = f.next() # get first line
hash_object = hashlib.md5 (line)
f1.write(hash_object.hexdigest()) # write to second file
答案 1 :(得分:0)
是的,应该在开头打开,并在完成后重复关闭。
因此,如果从文件中读取您想要读取的用户的输入,请说明如下:
import android
import hashlib
import time
name = 0
droid = android.Android()
f_in = open('input.txt', 'r',)
f_out = open('output.txt', 'w',)
for line in f_in.readlines():
hash_object = hashlib.md5 (line)
f_out.write(hash_object.hexdigest())
f_in.close()
f_out.close()