python - AttributeError: 'pyodbc.Row' object has no attribute 'JobCount' - python

I have a query that's grabbing data from a database and returning the values so I can parse.
def executeScriptsFromFile(monitor):
# Open and read the file as a single buffer
fd = open(os.path.join(BASE_DIR, 'sql/{0}.sql'.format(monitor)), 'r')
if args.alias:
sql_query = fd.read().format("'" + args.alias + "'")
else:
sql_query = fd.read()
fd.close()
# Execute SQL query from the input file
cursor.execute(sql_query)
result = cursor.fetchone()
return result
The query can differ so I'm trying to build in logic so it will skip part if JobCount isn't one of the values.
query_data = executeScriptsFromFile(args.monitor)
print query_data
if query_data.JobCount:
print query_data.JobCount
else:
send_status = send_data(job_data)
print send_status
Unfortunately I get the following traceback. How do I ignore the value if it isn't there?
Traceback (most recent call last):
File "tidal-zabbix.py", line 92, in <module>
if query_data.JobCount:
AttributeError: 'pyodbc.Row' object has no attribute 'JobCount'

If you want to check whether 'JobCount' is an attribute of query_data use hasattr()
if hasattr(query_data, 'JobCount'):
print query_data.JobCount
else:
send_status = send_data(job_data)
print send_status

Related

Converting excel to xml with Null values in excel

I'm trying to convert an excel file to xml using this skeleton code:
wb = load_workbook("deneme.xlsx")
# Getting an object of active sheet 1
ws = wb.worksheets[0]
doc, tag, text = Doc().tagtext()
xml_header = '<?xml version="1.0" encoding="UTF-8"?>'
# Appends the String to document
doc.asis(xml_header)
with tag('userdata'):
with tag('basicinf'):
for row in ws.iter_rows(min_row=2, max_row=None, min_col=1, max_col=90):
row = [cell.value for cell in row]
a=row[0]
with tag("usernumber"):
text(row[0])
with tag("username"):
text(row[1])
with tag("serviceareacode"):
text(row[2])
with tag("language"):
text(row[3])
with tag("welcomemsgid"):
text(row[4])
with tag("calledlimitedid"):
text(row[5])
with tag("followmeflag"):
text(row[6])
with tag("followmenumber"):
text(row[7])
with tag("mobilespecial"):
text(row[8])
result = indent(
doc.getvalue(),
indentation=' ',
indent_text=False
)
print(result)
with open("routescheme_{}.xml".format(a), "w") as f:
f.write(result)
Now if I don't write any input on row[0] in excel, I get the below error:
Traceback (most recent call last):
File "C:\Python39\lib\site-packages\yattag\simpledoc.py", line 489, in html_escape
return s.replace("&", "&").replace("<", "<").replace(">", ">")
AttributeError: 'NoneType' object has no attribute 'replace'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\abdul\Desktop\mmm\main.py", line 36, in <module>
text(row[0])
File "C:\Python39\lib\site-packages\yattag\simpledoc.py", line 179, in text
transformed_string = html_escape(strg)
File "C:\Python39\lib\site-packages\yattag\simpledoc.py", line 491, in html_escape
raise TypeError(
TypeError: You can only insert a string, an int or a float inside a xml/html text node. Got None (type <class 'NoneType'>) instead.
My expectation is that when row[0] is empty it should be like <usernumber></usernumber> in my xml result file.
How can I do that?
I guess ı found solution by myself. I am not sure this is a good solution but,
with tag("usernumber"):
if (row[0] == None):
text()
else:
text(row[0])
So if serviceare code is empty result is: <serviceareacode></serviceareacode>
if it is not empty, result is: <serviceareacode>value</serviceareacode>

why there is error on cancel qfiledialog?

That is my code
def report_one_friend(self):
filename = QFileDialog.getSaveFileName(self, "", "cars.xlsx","Excel(.xlsx)")
if filename:
openFile = open(filename, 'r').read()
self.plainTextEdit.appendPlainText(openFile)
wb = xlsxwriter.Workbook(filename[0])
sheet1 = wb.add_worksheet()
sql = '''SELECT * FROM ahmed WHERE mth_search = %s'''
mth_search = self.lineEdit_3.text()
c = self.conn.cursor()
c.execute(sql, [(mth_search)])
data = c.fetchall()
for row in data:
print(row)
sheet1.write(0,2,'الاسم')
sheet1.write(0,0,row[1])
sheet1.write(1, 2, 'الرقم')
sheet1.write(1, 0, row[2])
wb.close()
and that gives me an error :
Connected to MySQL database using C extension... MySQL Server version on 8.0.12
Traceback (most recent call last):
File "/Users/mahmoudtarek/Desktop/mth1/index.py", line 174, in mth_friends
self.report_one_friend()
File "/Users/mahmoudtarek/Desktop/mth1/index.py", line 208, in report_one_friend
openFile = open(filename, 'r').read()
TypeError: expected str, bytes or os.PathLike object, not tuple
you get a tuple of "the selected file" and "the applied filter".
minimal code example:
from PyQt5.Qt import *
app = QApplication([])
print(QFileDialog.getSaveFileName())
selected "some file":
('C:/scratches/scratch.py', 'All Files (*)')
But when you dont select something and cancel the dialog, then the two strings are empty: ('', '').
Because a tuple with two strings in it is true, you try to open() a file with this, which leads to you error.
Solution:
unpack the tuple into two variables or use index[0] like in the following:
filename, filter = QFileDialog.getSaveFileName(self, "", "cars.xlsx","Excel(.xlsx)")
if filename:
openFile = open(filename, 'r').read()
...

TypeError: first argument must be string or compiled pattern

I am fetching values from a database table called blocked_sites. If the value of 0th attribute in the table blocked_sites is present the 19th or 26th field of the file items.csv, then that row of the csv is to be excluded from the csv file. I am writing a code for that and getting this error:
$ python csv_dupli_prev.py
Traceback (most recent call last):
File "csv_dupli_prev.py", line 48, in <module>
found = re.search(row[0], row1[19])
File "/home/debarati/anaconda3/lib/python3.6/re.py", line 182, in search
return _compile(pattern, flags).search(string)
File "/home/debarati/anaconda3/lib/python3.6/re.py", line 300, in _compile
raise TypeError("first argument must be string or compiled pattern")
TypeError: first argument must be string or compiled pattern
The code is as follows:
connection = pymysql.connect (host = "localhost", user = "root", passwd = "......", db = "city_details")
cursor = connection.cursor ()
csv_file = csv.reader(open("items.csv", "r"))
newrows = []
cursor.execute ("select * from blocked_sites")
data4 = cursor.fetchall ()
for row in data4:
for row1 in csv_file:
str1 = row1[19]
str2 = row1[26]
found = re.search(row[0], str1)
found1 = re.search(row[0], str2)
if found==None and found1==None and row1 not in newrows:
newrows.append(row1)
writer = csv.writer(open("items.csv", "w"))
writer.writerows(newrows)
I changed the following line in my code:
cursor.execute ("select * from blocked_sites")
to this:
cursor.execute ("select content from blocked_sites")
and the bug got fixed.

AttributeError: 'tuple' object has no attribute 'write' error while writing into a file

from netmiko import ConnectHandler
from textfsm import *
cisco_device = { 'device_type' : 'cisco_ios', 'ip' : 'x.x.x.x', 'username':'gtomy200', 'password':'xxxxx'}
net_connect = ConnectHandler(**cisco_device)
fo=("testme.txt" , 'w')
output = net_connect.send_command("show int brief")
re_table = TextFSM(open('xr_show_int_br','r'))
data = re_table.ParseText(output)
print (output)
for s in re_table.header:
fo.write("%s;" %s)
fo.write("\n")
for row in data:
print (row)
for s in row:
fo.write("%s" %s)
fo.write("\n")
fo.close()
can someone help out, regarding the below error:
Traceback (most recent call last):
File "/Users/gtomy200/Desktop/Py/test.py", line 20, in
fo.write("%s;" %s)
AttributeError: 'tuple' object has no attribute 'write'
You want to ensure you open the file:
fo = open("testme.txt" , 'w')
# ^^^^
As it is you were trying to write to a two-tuple:
fo = ("testme.txt", 'w')
# ^ no open
which won't work.
fo is a tuple, use with open() for file operations. It's safier and easier.
with open ("myfile.txt","w") as ff:
ff.write("string") #you can't use anything but strings in here,
#so convert your variables to string

Python CSV Error

Hello all I keep getting this error while making a small program to sort large CSV files out, below is my code and error, what am I doing wrong?
if selection:
for stuff in stuffs:
try:
textFile = open("output.txt",'w')
mycsv = csv.reader(open(stuff))
d_reader = csv.DictReader(mycsv)
headers = d_reader.fieldnames <-- Error happens here
if selection in headers:
placeInList = headers.index(selection)
#placeInList = selection.index(selection)
for selection in tqdm(mycsv, desc='Extracting column values...', leave = True):
textFile.write(str(selection[int(placeInList)])+'\n')
print 'Done!'
textFile.close()
sys.exit()
except IOError:
print 'No CSV file present in directory'
sys.exit()
else:
sys.exit()
And the error:
Traceback (most recent call last):
File "postcodeExtractor.py", line 27, in <module> headers = d_reader.fieldnames
File "C:\Python27\lib\csv.py", line 90, in fieldnames self._fieldnames = self.reader.next()
TypeError: expected string or Unicode object, list found
instead of
mycsv = csv.reader(open(stuff))
d_reader = csv.DictReader(mycsv)
you want
d_reader = csv.DictReader(open(stuff))
the first line is the problem.

Categories