getting error "not all arguments converted during string formatting - Python" - python

I ma using csv file to fetch some data for automatic login. In my first file, lets call it core.py, i am defining it as function.Here is my code :
import csv
def csvTodict():
dir = os.path.dirname(__file__)
filename = os.path.join(dir, './testdata/InputData.csv')
with open(filename) as f:
logins = dict(filter(None, csv.reader(f)))
return logins
and in another file, i am calling the values for username and password : Its my modules.py
from core import *
fnsignin()
def fnsignin():
try:
myDict=csvTodict()
fnLogin(myDict["Username"],myDict["Password"]
But when i run, I am getting error " not all arguments converted during string formatting". I am not sure where I am doing wrong. Please help

Related

How to parse json in python

i want to get token through the result of REST API and it has done and success. the result of REST API shown below following print(result) of python
'{"UserId":"202","UserName":"xxx","UserMail":"yyy","Token":"abcdfghoijkalt"}'
do you know how to get "Token" as variable?, so i can get to next step. thank you
You can use json.loads
import json
jObject = json.loads('{"UserId":"202","UserName":"xxx","UserMail":"yyy","Token":"abcdfghoijkalt"}')
# This should give you the value you are looking for:
token = jObject["Token"]
print(token)
I have written a short write util function (below) which I include in every project I work on. So if your target file has a .json extension, it automatically format it into json.
eg. write(result, "dst_dir/dst_file.json")
import json
def write(content, file, **kwargs):
if not isinstance(file, str):
file = str(file)
if file.endswith('.json'):
with open(file, 'w') as f:
json.dump(content, f, indent=2, **kwargs)
else:
with open(file,'w') as f:
f.write(content, **kwargs)
write(result, "dst_dir/dst_file.json") # To run it with your result

Save variable in pc python

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)

How to write file name to use URL name in python?

I have an API scan of a large URL file, read that URL and get the result in JSON
I get the kind of url and domain like
google.com
http://c.wer.cn/311/369_0.jpg
How to change file format name using url name ".format (url_scan, dates)"
If I use manual name and it successfully creates a file, but I want to use it to read all URL names from the URL text file used for file name
The domain name is used for json file name and created successfully without errors
dates = yesterday.strftime('%y%m%d')
savefile = Directory + "HTTP_{}_{}.json".format(url_scan,dates)
out = subprocess.check_output("python3 {}/pa.py -K {} "
"--sam '{}' > {}"
.format(SCRIPT_DIRECTORY, API_KEY_URL, json.dumps(payload),savefile ), shell=True).decode('UTF-8')
result_json = json.loads(out)
with open(RES_DIRECTORY + 'HTTP-aut-20{}.csv'.format(dates), 'a') as f:
import csv
writer = csv.writer(f)
for hits in result_json['hits']:
writer.writerow([url_scan, hits['_date'])
print('{},{},{}'.format(url_scan, hits['_date']))
Only the error displayed when the http url name is used to write the json file name
So the directory is not a problem
Every / shown is interpreted by the system as a directory
[Errno 2] No such file or directory: '/Users/tes/HTTP_http://c.wer.cn/311/369_0.jpg_190709.json'
Most, if not all, operating systems disallow the characters : and / from being used in filenames as they have special meaning in URL strings. So that's why it's giving you an error.
You could replace those characters like this, for example:
filename = 'http://c.wer.cn/311/369_0.jpg.json google.com.json'
filename = filename.replace(':', '-').replace('/', '_')

Why is exec() command running with no errors but not producing the expected output?

I'm creating a very basic python program that allows a user to enter a command that is then ran as code.
For example I have imported a file called textScripts.py: within that file there is a function called createFile(). When the user enters textScripts.createFile() it is passed into exec(). It runs without error and exits the program but the file isn't created!
I know the createFile() function works because if I put textScripts.createFile() in the code it creates a file.
Here is the relevant snippet of code:
commandList=[]
while(commandRun):
count = 0
commandList.append(input(">>>"))
exec(commandList[count])
print(commandList[count])
count += 1
here is a screenshot of the code being run:
>>> textScripts.createFile()
>>>
here is a screenshot of the folder:
__pyCache__
textScripts.py
CLIFile.py
there should be a file in this folder
here is the function createFile():
def createFile(
destination = os.path.dirname(__file__),
text = "Sick With the Python\n"
):
''' createFile(destination, text)
This script creates a text file at the
Specified location with a name based on date
'''
date = t.localtime(t.time())
name = "%d_%d_%d.txt" %(date[1], date[2], date[0])
if not(os.path.isfile(destination + name)):
f = open(destination + name, "w")
f.write( text )
f.close
else:
print("file already exists")
I apologize in advance if this is an obvious questions; I'm new to python and have been looking for hours for an answer as to why this happens.
You save file to wrong folder (you can insert "print(destination + name)" in your function)
You need to replace this:
destination + name
to this:
os.path.join(destination, name)
PS:
You don't close the file (f.close -> f.close())
The best way to open any resource is using "with".
For example:
with open('file.txt', 'w') as f:
f.write('line')

Import a module with optional arguments python

Currently, I have a file called utils.py where I keep all my functions and another file called main.py.
In my utils file, I have a two functions that load and save to a json file, along with a bunch of other functions that will edit the data.
def save_league(league_name, records):
with open('%s.json' % league_name, 'w') as f:
f.write(json.dumps(records))
def load_league(league_name):
with open('%s.json' % league_name, 'r') as f:
content = f.read()
records = json.loads(content)
return records
I am trying to add optional arguments for the save_league function by changing the function to:
def save_league(name = league_name, r = records):
with open('%s.json' % name, 'w') as f:
f.write(json.dumps(r))
This way the file will save just from save_league().
However, when I try to import a function with optional arguments in main.py, I get a name error because the default arguments are not set at the beginning.
NameError: name 'league_name' is not defined
Is it possible import functions with optional args into another file or do I have to combine the two files into one?

Categories

Resources