Saving data in Python without a text file?

可紊 提交于 2019-12-13 21:34:09

问题


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?


回答1:


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.




回答2:


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.




回答3:


Why don't you just put it at the beginning of the code. E.g. 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



来源:https://stackoverflow.com/questions/17645420/saving-data-in-python-without-a-text-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!