Python connect mySQL database write to text file - python

I connect my python to MySQL server with mySQL-Connector(in pyCharm) and i can read from server then write text file.This seems to be:
(1, 'PENELOPE', 'GUINESS', datetime.datetime(2006, 2, 15, 4, 34, 33))
(2, 'NICK', 'WAHLBERG', datetime.datetime(2006, 2, 15, 4, 34, 33))
(3, 'ED', 'CHASE', datetime.datetime(2006, 2, 15, 4, 34, 33))
(4, 'JENNIFER', 'DAVIS', datetime.datetime(2006, 2, 15, 4, 34, 33))
(5, 'JOHNNY', 'LOLLOBRIGIDA', datetime.datetime(2006, 2, 15, 4, 34, 33))
I need to change the commas which are between two areas from , to ~ i can find source code could you help me ?Which class I do change?
this is my python code
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="2153417",
database="sakila"
)
tweets = open("keywords.txt", "w")
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM actor")
with open("C:/Users/Erhan/PycharmProjects/MySQL/keywords.txt", "w", newline='') as f:
for row in mycursor:
print(row, file=f)
this is working correctly just need change commas(,) among name,surname and datetime
like this
(1~ 'PENELOPE' ~ 'GUINESS' ~ datetime.datetime(2006, 2, 15, 4, 34, 33))
(2~ 'NICK' ~ 'WAHLBERG' ~ datetime.datetime(2006, 2, 15, 4, 34, 33))

Assuming you want the string representation of all objects(e.g 2006-02-15 04:34:33) instead of the objects representations datetime.datetime(2006, 2, 15, 4, 34, 33), try this:
As per your requirement, try this:
print(' ~ '.join(map(repr, row)), file=f)
I would recommend to try directly writing to the file instead:
f.write(' ~ '.join(map(repr, row))

Related

django error: "asc() got an unexpected keyword argument 'nulls_last' "

class CustomOrderFilter(OrderingFilter):
allowed_custom_filters = ['target_item__type_service', 'target_item__level', 'target_item__room__name',
'client__user_full_name', 'designer__user_full_name', 'status', 'date_due_decorist',
'target_item__date_answered']
def get_ordering(self, request, queryset, view):
params = request.query_params.get(self.ordering_param)
if params:
fields = [param.strip() for param in params.split(',')]
ordering = [f for f in fields if f.lstrip('-') in self.allowed_custom_filters]
if ordering:
return ordering
return self.get_default_ordering(view)
def filter_queryset(self, request, queryset, view):
order_fields = []
ordering = self.get_ordering(request, queryset, view)
if not ordering:
return queryset
order_fields.append(ordering[0])
if 'status' in order_fields or '-status' in order_fields:
ids = [0, 1, 2, 18, 3, 6, 9, 7, 21, 5, 8, 11, 12, 10, 14, 15, 16, 20, 4, 13, 17]
rev_ids = [11, 8, 5, 21, 7, 9, 6, 3, 18, 2, 1, 0, 12, 10, 14, 15, 16, 20, 4, 13, 17]
if '-status' in order_fields:
order = Case(*[When(status=id, then=pos) for pos, id in enumerate(rev_ids)])
else:
order = Case(*[When(status=id, then=pos) for pos, id in enumerate(ids)])
return queryset.order_by(order)
if '-date_due_decorist' in order_fields:
return queryset.order_by(F('date_due_decorist').desc(nulls_last=True))
elif 'date_due_decorist' in order_fields:
return queryset.order_by(F('date_due_decorist').asc(nulls_last=True))
return queryset.order_by(ordering[0])
In custom ordering django, I am getting error as "asc() got an unexpected keyword argument 'nulls_last' ". I want to show null values always at last in date_due_decorist column while sorting. Please let me know if django version 1.10 supports 'nulls_last' or not.
If not support then let me know how can this be done?

Printing error with python class attributes, where have I gone wrong?

I'm trying to print a select row and columns from a spreadsheet, however when I call on the spreadsheet dataframe attribute it fails to print state that the name dataframe is not defined. where have I gone wrong?
import pandas
class spreadsheet:
def __init__(self, location, dataframe, column, rows):
self.location = ('Readfrom.xlsx')
self.dataframe = pandas.read_excel(location)
self.column = 2
self.rows = 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 27, 28, 29
a = dataframe.iloc[column,[rows]]
print(a)
You should instantiate an object from the Spreadsheet class and then access the attribute of the instance. You can learn more about Object-Oriented Programming in Python here.
I think that what you want to do in your code is something like the code below.
import pandas
class Spreadsheet:
def __init__(self, location):
self.location = location
self.dataframe = pandas.read_excel(location)
sp = Spreadsheet(location="Readfrom.xlsx")
rows = [4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 27, 28, 29]
a = sp.dataframe.iloc[rows, 2]
print(a)
I think you have an indentation problem.
Your dataframe is a parameter of your spreadsheet constructor method and you try to access it even from outside the class.
To access the dataframe variable u have to move your code a = dataframe.iloc[column,[rows]] inside your __init__ method or you need to create a spreadsheet object first and access it via this object.
EDIT:
On second thoughts i think you should check out the basics how to use classes in Python.
You don't use the parameters of the __init__ so why du you have them?
dataframe is only accessible by a spreadsheet object
This code should fix your problem but i recommend to go through some basic tutorials to understand how exactly classes and objects are working:
import pandas
class spreadsheet:
def __init__(self):
self.location = ('Readfrom.xlsx')
self.dataframe = pandas.read_excel(self.location)
self.column = 2
self.rows = 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 27, 28, 29
s = spreadsheet()
a = s.dataframe.iloc[s.column,[s.rows]]
print(a)

storing student data in python list to get percentage

import re
import os
import sys
class Marks:
def __init__(self):
self.marks = []
self.marks_file = '/root/projectpython/mark.txt'
def loadAll(self):
file = open(self.marks_file, 'r')
for line in file.readlines():
name,math,phy,chem = line.strip().split()
name=name
math=int(math)
phy=int(phy)
chem=int(chem)
self.marks=[name,math,phy,chem]
print(self.marks)
file.close()
def percent(self):
dash = '-' * 40
self.loadAll()
for n in self.marks:
print(n)
Book_1 = Marks()
Book_1.percent()
output:-
['gk', 50, 40, 30]
['rahul', 34, 54, 30]
['rohit', 87, 45, 9]
rohit
87
45
9
but i want to print all value in tabular format,it showing only last record.
is it correct method to use list to store student data name and marks.
problem here is with the line read
self.marks=[name,math,phy,chem]
this will keep reinitializing the list each time mark is read
instead use:
self.marks.append([name,math,phy,chem])
You continue to initialize the list in the for statement
and declare it so that only the array value of the last line is reflected.
I think you can remove the initialization statement and process it as an append.
import re
import os
import sys
class Marks:
def __init__(self):
self.marks = []
self.marks_file = '/root/projectpython/mark.txt'
def loadAll(self):
file = open(self.marks_file, 'r')
for line in file.readlines():
name,math,phy,chem = line.strip().split()
name=name
math=int(math)
phy=int(phy)
chem=int(chem)
self.marks.append(name)
self.marks.append(math)
self.marks.append(phy)
self.marks.append(chem)
# self.marks=[name,math,phy,chem]
print(self.marks)
file.close()
def percent(self):
dash = '-' * 40
self.loadAll()
for n in self.marks:
print(n)
Book_1 = Marks()
Book_1.percent()
Make self.marks=[name,math,phy,chem] as self.marks.append([name,math,phy,chem]).
Then easiest solution is to transpose the self.marks list and print them.
suppose your marks list is [['gk', 50, 40, 30],['rahul', 34, 54, 30],['rohit', 87, 45, 9]] then simply transpose it.
print(marks)
transposed=list(zip(*marks))
print(transposed)
for x in transposed:
print(x)
output :
[['gk', 50, 40, 30], ['rahul', 34, 54, 30], ['rohit', 87, 45, 9]] #marks list
[('gk', 'rahul', 'rohit'), (50, 34, 87), (40, 54, 45), (30, 30, 9)] #transposed list
('gk', 'rahul', 'rohit') # output the way you want
(50, 34, 87)
(40, 54, 45)
(30, 30, 9)
Its working now.
i was doing mistake earlier here only self.marks.append([name,math,phy,chem])
[['gk', 50, 40, 30], ['rahul', 34, 54, 30], ['rohit', 87, 45, 9]]

Retrieve MSSQL datetime2(7) value as Python datetime with microseconds rounded instead of truncated

If I do a CAST in T-SQL, 0397 is rounded to 040 with proper rounding, but pyodbc truncates it to 039. How can I easily do this rounding like SQL Server does it?
1> select logid, timestamputc from eventlog where logid=166944;
2> go
logid timestamputc
-------------------- --------------------------------------
166944 2017-05-30 08:59:37.6650397
1> select logid from eventlog
where cast(timestamputc as datetime2(6))='2017-05-30 08:59:37.665039';
2> go
logid
--------------------
(0 rows affected)
1> select logid from eventlog
where cast(timestamputc as datetime2(6))='2017-05-30 08:59:37.665040';
2> go
logid
--------------------
166944
with pyodbc:
[{'logid': 166944, 'timestamputc': '2017-05-30 08:59:37.665039'}]
As you've discovered, when pyodbc retrieves a datetime2(7) column as a Python datetime object its default behaviour is to truncate the seventh decimal place. If you want the datetime object to be rounded, as SQL Server would return a datetime2(7) value CAST to datetime2(6), then you can use an output converter function.
For example, if you define your output converter function as
def handle_datetime2(dt2_value):
tup = struct.unpack("<6hI", dt2_value) # e.g., (2017, 5, 30, 8, 59, 37, 0, 665039700)
return datetime(tup[0], tup[1], tup[2],
hour=tup[3], minute=tup[4], second=tup[5],
microsecond=math.floor(tup[6] / 1000.0 + 0.5))
and use it like this
cnxn = pyodbc.connect(conn_str, autocommit=True)
crsr = cnxn.cursor()
cnxn.add_output_converter(pyodbc.SQL_TYPE_TIMESTAMP, handle_datetime2)
dt_string = '2017-05-30 08:59:37.6650397'
dt_value = crsr.execute(f"SELECT CAST('{dt_string}' AS DATETIME2(7))").fetchval()
print(f'{dt_string}\n -> {repr(dt_value)}')
dt_string = '2017-05-30 08:59:37.6650395'
dt_value = crsr.execute(f"SELECT CAST('{dt_string}' AS DATETIME2(7))").fetchval()
print(f'{dt_string}\n -> {repr(dt_value)}')
dt_string = '2017-05-30 08:59:37.6650394'
dt_value = crsr.execute(f"SELECT CAST('{dt_string}' AS DATETIME2(7))").fetchval()
print(f'{dt_string}\n -> {repr(dt_value)}')
the results will look like this
2017-05-30 08:59:37.6650397
-> datetime.datetime(2017, 5, 30, 8, 59, 37, 665040)
2017-05-30 08:59:37.6650395
-> datetime.datetime(2017, 5, 30, 8, 59, 37, 665040)
2017-05-30 08:59:37.6650394
-> datetime.datetime(2017, 5, 30, 8, 59, 37, 665039)

convert variables into dictonaries

I have something like this where trade_date, effective_date and termination_date are date values:
tradedates = dict(((k, k.strftime('%Y-%m-%d'))
for k in (trade_date,effective_date,termination_date)))
I get this:
{datetime.date(2005, 7, 25): '2005-07-25',
datetime.datetime(2005, 7, 27, 11, 26, 38): '2005-07-27',
datetime.datetime(2010, 7, 26, 11, 26, 38): '2010-07-26'}
What I would like is:
{'trade_date':'2005-07-25','effective_date':'2005-07-27','termination_date':'2010-07-26'}
How do I achieve this?
Using vars:
>>> import datetime
>>>
>>> trade_date = datetime.date(2005, 7, 25)
>>> effective_date = datetime.datetime(2005, 7, 27, 11, 26, 38)
>>> termination_date = datetime.datetime(2010, 7, 26, 11, 26, 38)
>>>
>>> d = vars() # You can access the variable as d['name']
>>> tradedates = {
... name: d[name].strftime('%Y-%m-%d')
... for name in ('trade_date', 'effective_date', 'termination_date')
... }
>>> tradedates
{'effective_date': '2005-07-27', 'termination_date': '2010-07-26', 'trade_date': '2005-07-25'}
For something that size, I'd create the dict directly:
result = {
'trade_date': format(trade_date, '%Y-%m-%d'),
'effective_date': format(effective_date, '%Y-%m-%d'),
# etc....
}
I am not sure if I got your question right. But let me explain what I understood and my answer for that:
You know the variable names: trade_date,effective_date,termination_date
And they have data in them
You could easily do:
tradedates = dict()
for k in ('trade_date','effective_date','termination_date'):
tradedates[k] = eval(k).strftime('%Y-%m-%d') // eval will evaluate them as a variable name not as a string.
This will give you a final dict something like:
{
'trade_date': <date_string_according_to_the_format_above>
'effective_date': <date_string_according_to_the_format_above>
'termination_date': <date_string_according_to_the_format_above>
}

Categories