The best way to open two files

user3530608 picture user3530608 · Jul 11, 2014 · Viewed 7.6k times · Source

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

Answer

Padraic Cunningham picture Padraic Cunningham · Jul 11, 2014

If you want to read from the file name.txt and write to another:

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