[英]What is the best way to open multiple files in python when I have the name of the files stored in a list?
[英]The best way to open two files
我需要打开一个文件,读取一行,对其进行哈希处理,然后保存到另一个文件中。 我应该在脚本开头打开两个文本文件,还是每次保存/读取时都打开? 我是这一切的新手,我正在为 sl4a 使用 python for android。 到目前为止,这是我的代码:
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()
如果要从文件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
Yes 应该在开始时打开,并在完成后迭代关闭。
因此,不要从用户那里读取输入,而是从文件中读取,而是这样说:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.