Variable name to string in Python

2024/11/16 5:57:39

I have written some code in Python and I would like to save some of the variables into files having the name of the variable.

The following code:

variableName1 = 3.14
variableName2 = 1.09
save_variable_to_file(variableName1) # function to be defined
save_variable_to_file(variableName1)

should create 2 files, one named variableName1.txt and the other one variableName2.txt and each should contain the value of the corresponding variable at the time the function was called.

This variable name is supposed to be unique in the code.

Thanks!

HM

Answer

It is possible to find the name of a variable, a called function can get its caller's variables using:

import sysdef save_variable_to_file(var):names = sys._getframe(1).f_globalsnames.update(sys._getframe(1).f_locals)for key in names.keys():if names[key] == var: breakif key:open(key+".txt","w").write(str(var))else:print(key,"not found")thing = 42
save_variable_to_file(thing)

But it is probably a really bad idea. Note that I have converted the value to a string, how would you want dictionaries and lists to be saved? How are you going to reconstruct the variable later?

import globfor fname in glob.iglob("*.txt"):vname = fname.rstrip(".txt")value = open(fname).read()exec(vname + "=" + value)print(locals())

Using something like exec can be a security risk, it is probably better to use something like a pickle, JSON, or YAML.

https://en.xdnf.cn/q/71700.html

Related Q&A

In Python, how to print FULL ISO 8601 timestamp, including current timezone

I need to print the FULL local date/time in ISO 8601 format, including the local timezone info, eg:2007-04-05T12:30:00.0000-02:00I can use datetime.isoformat() to print it, if I have the right tzinfo o…

TextVariable not working

I am trying to get the Text out of an Entry widget in Tkinter. It works with Entry1.get(), but it does not work using textvariableWhat am I doing wrong ? from Tkinter import * master = Tk() v = String…

Is there a Python module to get next runtime from a crontab-style time definition?

Im writing a dashboard application and I need a way to figure out how long an item is "valid", i.e. when should it have been superseded by a new value (its possible to have an error such that…

Django Generic Relations error: cannot resolve keyword content_object into field

Im using Djangos Generic Relations to define Vote model for Question and Answer models. Here is my vote model:models.pyclass Vote(models.Model):user_voted = models.ForeignKey(MyUser)is_upvote = models.…

How to benchmark unit tests in Python without adding any code

I have a Python project with a bunch of tests that have already been implemented, and Id like to begin benchmarking them so I can compare performance of the code, servers, etc over time. Locating the …

Digit recognition with Tesseract OCR and python

I use Tesseract and python to read digits (from a energy meter). Everything works well except for the number "1". Tesseract can not read the "1" Digit.This is the picture I send t…

Pycharm not recognizing packages even when __init__.py exits

This is my directory structure--> ProjectDirectory-->__init__.py--> BaseDirectory-->__init__.py--> AnotherBaseDirectory-->__init__.py-->program.pyinside program.pyWhen i give impor…

Scrapy is following and scraping non-allowed links

I have a CrawlSpider set up to following certain links and scrape a news magazine where the links to each issue follow the following URL scheme:http://example.com/YYYY/DDDD/index.htm where YYYY is the …

Overriding virtual methods in PyGObject

Im trying to implement the Heigh-for-width Geometry Management in GTK with Python for my custom Widget. My widget is a subclass from Gtk.DrawingArea and draws some parts of an Image.As I understood the…

How to find if two numbers are consecutive numbers in gray code sequence

I am trying to come up with a solution to the problem that given two numbers, find if they are the consecutive numbers in the gray code sequence i.e., if they are gray code neighbors assuming that the …