简体   繁体   中英

Saving data in Python without a text file?

I have a python program that just needs to save one line of text (a path to a specific folder on the computer).

I've got it working to store it in a text file and read from it; however, I'd much prefer a solution where the python file is the only one.

And so, I ask: is there any way to save text in a python program even after its closed, without any new files being created?

EDIT: I'm using py2exe to make the program an .exe file afterwards: maybe the file could be stored in there, and so it's as though there is no text file?

You can save the file name in the Python script and modify it in the script itself, if you like. For example:

import re,sys

savefile = "widget.txt"
x = input("Save file name?:")
lines = list(open(sys.argv[0]))
out = open(sys.argv[0],"w")
for line in lines:
    if re.match("^savefile",line):
        line = 'savefile = "' + x + '"\n'
    out.write(line)

This script reads itself into a list then opens itself again for writing and amends the line in which savefile is set. Each time the script is run, the change to the value of savefile will be persistent.

I wouldn't necessarily recommend this sort of self-modifying code as good practice, but I think this may be what you're looking for.

Seems like what you want to do would better be solved using the Windows Registry - I am assuming that since you mentioned you'll be creating an exe from your script.

This following snippet tries to read a string from the registry and if it doesn't find it (such as when the program is started for the first time) it will create this string. No files, no mess... except that there will be a registry entry lying around. If you remove the software from the computer, you should also remove the key from the registry. Also be sure to change the MyCompany and MyProgram and My String designators to something more meaningful.

See the Python _winreg API for details.

import _winreg as wr

key_location = r'Software\MyCompany\MyProgram'
try:
    key = wr.OpenKey(wr.HKEY_CURRENT_USER, key_location, 0, wr.KEY_ALL_ACCESS)
    value = wr.QueryValueEx(key, 'My String')
    print('Found value:', value)
except:
    print('Creating value.')
    key = wr.CreateKey(wr.HKEY_CURRENT_USER, key_location)
    wr.SetValueEx(key, 'My String', 0, wr.REG_SZ, 'This is what I want to save!')
wr.CloseKey(key)

Note that the _winreg module is called winreg in Python 3.

Why don't you just put it at the beginning of the code. Eg start your code:

import ... #import statements should always go first

path = 'what you want to save'

And now you have path saved as a string

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