I have a script that loops through file names in a json doc. In the event that there are no more filenames, I have a break statement that breaks the loop and stores the last read filename in a variable to print. Is there a way to save this variable so when I call the script again, it can use the last read filename as the starting point?
Thanks in advance
You could save it to a dotenv file or use configparser to save it to a ini and then retrieve it the same way.
To write just do
with open('yourfile.ini', 'wb') as config:
config.write(yourvariable_info)
This is a snippet I had to retrieve variables:
from configparser import ConfigParser
def config(filename='/home/pi/your/directory.ini', section='postgresql'):
# create a parser
parser = ConfigParser()
# read config file
parser.read(filename)
# get section, default to postgresql
db = {}# retrieves a dictionary
if parser.has_section(section):
params = parser.items(section)
for param in params:
db[param[0]] = param[1]
else:
raise Exception('Section {0} not found in the {1} file'.format(section, filename))
return db
Related
I want to save a variable (user input fo mail) in pc. Because I don't want it to ask to login again and again. So please help me with how to store email variable in pc and also how to access it. Thank you.
I'm not sure what you want exactly.
If you just wanna save a text(I mean, string) in variable, then write it to a file like this.
f = open("some_file_to_save.txt", 'w')
f.write(your_variable)
f.close()
Or if you want data to be loaded as python variable again, then you can utilize pickle
May be you need config to your program?
So for this use the configparser
import configparser
You need 2 functions, first to Save:
def save_config(email):
config = configparser.ConfigParser()
config['DEFAULT'] = {
'Email': email
}
with open('config.ini', 'w') as configfile:
config.write(configfile)
And second to read saved data:
def read_config():
config = configparser.ConfigParser()
config.read('config.ini')
return config['DEFAULT']['Email']
Then add it to your code or use this example:
try:
email = read_config()
except:
print("Config doest contain email, type it:")
email = input()
print(f"My email is {email}")
save_config(email)
I'm trying to write a dictionary to a file.
and when I try to read it back, it returns nothing, as if the file is empty.
I saw the file and there is something written into it.
I think that the way I write is not the best and that's why it does the problem.
my expected outcome is to read the file, get back the dictionary, and write to it. This is how I write:
# this function gets the db_name, creating a text file with the db_name
# and creating a empty dictionary with the key that is the table_name.
def __createTheDb(self,dirPath, db_name, table_name):
global db_file
os.chdir(dirPath) #gets into the directory
print(os.getcwd(), "from create the db")
db_file = open(db_name + ".txt", "w")
temp_dict = dict.fromkeys(f"{table_name}".split())
db_file.write(str(temp_dict))
return db_file
How I write the file:
def writeFile(self, db_name, table_name, key, value):
global db_file, my_json #gets the global variable
print(type(db_file))
file = open(db_name,"r").read()
print(file) #-> the problem is that this prints nothing.
I tried to read it with json.load(db_file), but it says it's unreadable.
The problem ->
return loads(fp.read(),
io.UnsupportedOperation: not readable
I just want to convert the text file to dictionary so I can set it's key...
try loading it with
with open("./path/file.json", "r") as f:
loadedDic = json.load(f)
then loadedDic will be equal to the dictionary IF the file you loaded is just a dictionary. If it has a list of dictionaries, or a dictionary of dictionaries, etc you'll need to parse it the way you normally parse lists/dicts/etc.
I'm trying to write some basic code to retrieve the list of workspaces and write the response to a file. I thought that this could be dumped to a JSON file?
Thanks for any help/suggestions.
I have taken the sample .py file and reworked it to look like this -
# Install the smartsheet sdk with the command: pip install smartsheet-python-sdk
import smartsheet
import logging
import os.path
import json
# TODO: Set your API access token here, or leave as None and set as environment variable "SMARTSHEET_ACCESS_TOKEN"
access_token = None
print("Starting ...")
# Initialize client
smart = smartsheet.Smartsheet(access_token)
# Make sure we don't miss any error
smart.errors_as_exceptions(True)
# Log all calls
logging.basicConfig(filename='rwsheet.log', level=logging.INFO)
response = smart.Workspaces.list_workspaces(include_all=True)
workspaces = response.data
with open('data.json', 'w') as outfile:
json.dump(workspaces, outfile)
print("Done")
I'm not sure what issue you are facing, but I think you would have an issue with the json.dump(workspaces, outfile) line as the results of that workspaces variable is a list that you would need to iterate through to get through the data. Using that variable will just print out the pointer with something like this:
[<smartsheet.models.workspace.Workspace object at 0x10382a4e0>]
To work around this you would need to loop over the results of the variable and print them each out to a file. I found this post here about printing output to a file. The answer gives three approaches and I was able to get each of them to work with a loop iterating over the results.
One example:
import smartsheet
smar_client = smartsheet.Smartsheet(<ACCESS_TOKEN>)
response = smar_client.Workspaces.list_workspaces(include_all=True)
workspaces = response.data
with open('workspaces.json', 'w') as f:
for workspace in workspaces:
print(workspace, file=f)
Running this gave me a workspaces.json file in the same directory I ran my script from with the list of workspace objects.
i'm writing a script in Python doing a while true cicle, how can I make my script take the same file abc123.json for each cicle and modify some variables in it?
If I understand your question correctly, you want to read a file named abc123.json somewhere on a local hard drive that is accessible via path and modify a value for a key (or more) for that json file, then re-write it.
I'm pasting an example of some code I used a while ago in hopes it helps
import json
from collections import OrderedDict
from os import path
def change_json(file_location, data):
with open(file_location, 'r+') as json_file:
# I use OrderedDict to keep the same order of key/values in the source file
json_from_file = json.load(json_file, object_pairs_hook=OrderedDict)
for key in json_from_file:
# make modifications here
json_from_file[key] = data[key]
print(json_from_file)
# rewind to top of the file
json_file.seek(0)
# sort_keys keeps the same order of the dict keys to put back to the file
json.dump(json_from_file, json_file, indent=4, sort_keys=False)
# just in case your new data is smaller than the older
json_file.truncate()
# File name
file_to_change = 'abc123.json'
# File Path (if file is not in script's current working directory. Note the windows style of paths
path_to_file = 'C:\\test'
# here we build the full file path
file_full_path = path.join(path_to_file, file_to_change)
#Simple json that matches what I want to change in the file
json_data = {'key1': 'value 1'}
while 1:
change_json(file_full_path, json_data)
# let's check if we changed that value now
with open(file_full_path, 'r') as f:
if 'value 1' in json.load(f)['key1']:
print('yay')
break
else:
print('nay')
# do some other stuff
Observation: the code above assumes that both your file and the json_data share the same keys. If they dont, your function will need to figure out how to match keys between data structures.
Is there a parser which reads and stores the types of data to write?
File format must to produce a readable.
Shelve does not offer.
Use the ConfigParser class to read configuration files in the ini file format:
http://docs.python.org/library/configparser.html#examples
The ini file format does not store the datatype of the values stored (you need to know them as you read the data back). You could overcome this limitation by encoding your values in json format:
import simplejson
from ConfigParser import ConfigParser
parser = ConfigParser()
parser.read('example.cfg')
value = 123
#or value = True
#or value = 'Test'
#Write any data to 'Section1->Foo' in the file:
parser.set('Section1', 'foo', simplejson.dumps(value))
#Now you can close the parser and start again...
#Retrieve the value from the file:
out_value = simplejson.loads(parser.get('Section1', 'foo'))
#It will match the input in both datatype and value:
value === out_value
Being json, the format of the stored value is human readable.
You could use the following function
def getvalue(parser, section, option):
try:
return parser.getint(section, option)
except ValueError:
pass
try:
return parser.getfloat(section, option)
except ValueError:
pass
try:
return parser.getbool(section, option)
except ValueError:
pass
return parser.get(section, option)
With configobj library, it becomes very simple.
import sys
import json
from configobj import ConfigObj
if(len(sys.argv) < 2):
print "USAGE: pass ini file as argument"
sys.exit(-1)
config = sys.argv[1]
config = ConfigObj(config)
Now you can use config as a dict to extract the desired configuration.
If you want to convert it to json, that's simple too.
config_json = json.dumps(config)
print config_json