Search code examples
pythonfiletextsl4a

The best way to open two files


I need to open a file, read a line, hash it, and then save to a different file. Should I open both text files at the beginning of my script, or should I open each every time I save/read? I'm new to all this and I'm using python for android for sl4a. This is my code so far:

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()

Solution

  • Yes should open both at the beginning and iterate through closing when you are done.

    so instead of reading input from the user you want to read if from a file, say something like this:

    import android
    import hashlib
    import time
    name = 0
    droid = android.Android()
     
    with open('input.txt', 'r') as f_in, open('output.txt', 'w') as f_out:
    for line in f_in.readlines():
        hash_object = hashlib.md5 (line)
        f_out.write(hash_object.hexdigest())