简体   繁体   中英

.txt file is empty after writing from python script --/— passing decryption key

I'm trying to create a script for appending/changing/retrieving passwords from a .txt file acting as a password manager.

When researching the history of the question being asked here, it seems the issue for most users is that they forget to flush() or close() their file stream.

theList = {}

# Populates theList with pairs
def getData():
    with open('pass_data.txt', 'w+') as data:
        for line in data:
            keyValuePair = line.split()
            theList[keyValuePair[0]] = keyValuePair[1]

# Writes pairs from theList to file 'pass_data.txt'
def putData():
    with open('pass_data.txt', 'w+') as data:
        for k, v in theList.items():
            data.writelines([k, ' ', v, "\n"])
        data.flush()

# Appends new pair to theList or overwrites if already exists
def setPass(service, password):
    getData()
    theList[service] = password
    putData()

# Retrieves password from given key 'service'
def getPass(service):
    getData()
    print theList[service]

I added flush() after reading up on the issue and it makes no difference...my .txt is still empty and I can't getPass('service') when calling the function from the command line because it says there is no key value 'service'.


I have a second question that someone may be able to answer for me here as well. If I encrypt the pass_data.txt file with blowfish from vim vim -u ~/.vimrc_encrypted -x pass_data.txt , is there a way I can pass the key for decrypting the file as an argument for setPass() and getPass() ?

From the docs :

Modes 'r+', 'w+' and 'a+' open the file for updating (reading and writing); note that 'w+' truncates the file. Append 'b' to the mode to open the file in binary mode, on systems that differentiate between binary and text files; on systems that don't have this distinction, adding the 'b' has no effect.

In getData you are basically truncating your file before reading it, thus it appears empty.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM