I am trying to put this piece of code into a function so that i can avoid just copy pasting the code everytime. Here the code that I want to put in a function:
f= open("test.txt","w+")
os.chdir("//10.2.30.61/c$\Qlikview_Tropal/apps/ventes")
for fichiers in glob.glob("*"):
today = datetime.datetime.today()
modified_date = datetime.datetime.fromtimestamp(os.path.getmtime(fichiers))
duration = today - modified_date
if duration.days < 1:
f.write(f"{fichiers} = {duration} \n")
edit1: I have changed my code like Chepner's advice now the issue still remains that there is no output being written to my test.txt file.
What am I missing ?
Thanks alot!
As is, you don't need any parameters (though I'm going to re-write it slightly to use a with statement):
def my_function():
with open("test.txt", "w+") as f:
os.chdir("//10.2.30.61/c$\Qlikview_Tropal/apps/ventes")
for fichiers in glob.glob("*"):
today = datetime.datetime.today()
modified_date = datetime.datetime.fromtimestamp(os.path.getmtime(fichiers))
duration = today - modified_date
if duration.days < 1:
f.write(f"{fichiers} = {duration} \n")
my_function()
You might want to parameterize the function in several ways, however. Both the hard-coded output file name and the input directory are candidates.
def my_function(output_name, input_dir):
with open(output_name, "w+") as f:
os.chdir(input_dir)
for fichiers in glob.glob("*"):
today = datetime.datetime.today()
modified_date = datetime.datetime.fromtimestamp(os.path.getmtime(fichiers))
duration = today - modified_date
if duration.days < 1:
f.write(f"{fichiers} = {duration} \n")
my_function("test.txt", "//10.2.30.61/c$\Qlikview_Tropal/apps/ventes")
There's no one answer to this question. It depends on how you want to reuse this function. You can start by asking yourself these questions:
Will I always have to open the same file i.e. test.txt or if it not, you can set it as an argument.
Will I always change directory to the same folder i.e. "//10.2.30.61/c$\Qlikview_Tropal/apps/ventes"
Will I always write the same text to files i.e {fichiers} = {duration} \n
If these things change in different context, you can make them arguments. But, if everything will be the same, you can just define a function without any arguments.
If you just want to have a function without any parameter you can do like:
def my_function():
f= open("test.txt","w+")
os.chdir("//10.2.30.61/c$\Qlikview_Tropal/apps/ventes")
for fichiers in glob.glob("*"):
today = datetime.datetime.today()
modified_date = datetime.datetime.fromtimestamp(os.path.getmtime(fichiers))
duration = today - modified_date
if duration.days < 1:
f.write(f"{fichiers} = {duration} \n")
Call it simply like: my_function()
Function with parameters: Based on the code you have provided, you can keep file name and url as parameters to the function like:
Functions with parameters can be used again and again with different parameters
def my_function(fileName, URL):
f= open(fileName,"w+")
os.chdir(URL)
for fichiers in glob.glob("*"):
today = datetime.datetime.today()
modified_date = datetime.datetime.fromtimestamp(os.path.getmtime(fichiers))
duration = today - modified_date
if duration.days < 1:
f.write(f"{fichiers} = {duration} \n")
Then call it like:
my_function("test.txt", "//10.2.30.61/c$\Qlikview_Tropal/apps/ventes")
Related
I am kind of a beginner in python and stuck with the part where I have to access methods from a class which reside in a different file.
Here, in File1 i am trying to access find_method from file2 to and do some operation and return values. But somehow its not accessing "find_method" from file2.
id_1.py (File1):
from base_file import base_file
class id_1:
def condition():
day_part_response = ...some response...
current_time = ...some value...
abc = basefile.find_method(x=day_part_response, y=current_time)
base_file.py (File2)
class basefile:
def find_method(self, x, y):
for day in day_response:
start = day["start_time"]
end = day["end_time"]
if (condition): -->(consider this condition is satisfied)
self.start_time = start
self.end_time = end
day_id = day["_id"]
self.entity_ID = day["entity_id"]
self.restore = True
self.create_entity()
return self.start_time, self.end_time, day_id, self.day_part_entity_ID, self.restore
You will need to import using from base_file import basefile. Make sure to use above import statement, your both files 1 & 2 are in same directory.
In base_file.py, check if for your given input satisfies the condition -
if start < end and start < store_time < end or \
end < start and not (end < store_time < start):
otherwise it won't return any result and None will get returned as default.
In id_1.py, check if you are creating instance of the class id_1 like -
id_1_instance = id_1()
and then call the condition method on the instance
id_1_instance.condition()
Since above call receives a returned value, make sure to print it so you can see the output.
You should be doing: from base_file import basefile
If 'base_file.py' is in the same directory as id_1.py
then the import will work. If you put the class in a
different directory, you need to add a line of code
before the import, something like:
sys.path.append("/home/username/python/classes")
You should also take a look at https://peps.python.org/pep-0008/#class-names
which gives you the recommended naming conventions such as:
methods should be in the 'snake' format: def my_method().
Class names should follow the 'camelcase'.
The class MyNewClass() should be saved in a file named: myNewClass.py
So, you would do the import as: from myNewClass import MyNewClass.
I save all my classes in a single 'class' directory.
Of course if you are using Windows, you would have to specify
"C:\whatever".
Hope this helps!
I have a program that I want to be able to print all of the instances of each variable using my method that I created. Problem is I can't figure out a way to print them since each are listed under a different variable that aren't configured from hardcoding them in and I need a way to automatically recall them in my code.
class fit:
def __init__(self,day,did,workout='Not Recorded',time='An unknown amount of',calories='An unknown amount of'):
self.day = day
self.did = did
if did.lower()=='no':
self.workout = 'Not Recorded'
self.time = "An unknown amount of Minutes"
self.calories = "An unknown amount of Calories"
else:
self.workout = workout
self.time = "{} Minutes".format(time)
self.calories = "{} Calories".format(calories)
def formate(self):
self.formate = "{}:\n\nDid you work out: {}\nWorkout focus: {}\nYou worked out for: {}\nYou burned: {}\n\n----------------------------------------------------------".format(self.day,self.did,self.workout,self.time,self.calories)
return self.formate
def reader(day,index):
file = open('readme.txt')
file = file.read()
stripped = file.rsplit("\n")
for i in range(len(stripped)):
stripped[i] = stripped[i].rsplit(" ")
del stripped[-1]
if int(index) >= len(stripped[day-1]):
return "none"
else:
return stripped[day-1][index]
x = 0
def create_new_instance(class_name,instance_name):
globals()[instance_name] = class_name(reader(x,0),reader(x,1),reader(x,2),reader(x,3),reader(x,4))
print('Class instance {} created'.format(instance_name))
while True:
try:
x+=1
ins = 'day_' + str(x)
create_new_instance(fit,ins)
except:
break
break
def printer(instance):
print(.formate())
while True:
x+=1
inst = 'day_' + str(x)
printer(inst)
An example of this might be that I have 8 lines of data from a text document and I have a system that creates instances of day_1, day_2, day_3 ect until day_8 and then I want to print each of those instances out, but again I don't have those instances directly hardcoded into my code so I don't know how I'd do it. I've tried looking into maybe a while loop and increasing a variable by 1 and concatenating it with day and trying to make a variable out of that but the my limited experience with python isn't helping.
A very unpythonic and ugly way would be to use exec, for example:
day_3=5
x = 'day_'+'3'
exec("print("+x+")")
I would recommend another way to store your variables though.
When I call on datetime.now() in my program it calls the current time, but when I call it again, it displays the previous time. How can I update datetime.now() so it calls the current time eachtime?
You say:
but when I call it again
... but you're NOT calling it again. You're more-than-likely printing/outputting the value of the variable that the first datetime.now() was assigned to.
Let's say you have the following:
from datetime import datetime
first_time = str(datetime.now())
print('First datetime.now() value: %s' % first_time)
You're probably attempting to get the updated time by simply printing first_time (what you incorrectly refer to as "calling").
Instead, you should either overwrite first_time by reassigning datetime.now() to it, or you should declare a new variable and assign datetime.now() to it.
# Overwriting & outputting:
# first_time = datetime.now()
# Declaring a new (updated) value (what I'll use in the example):
second_time = datetime.now()
# Outputting:
print('first_time: %s\nsecond_time: %s' % (str(first_time), str(second_time)))
You can define as follows:
def now():
return datetime.datetime.now().strftime('%d.%m.%Y %H:%M:%S')
use the definition in the following way:
print('{}'.format(now()))
I have a model like this;
starttime = models.TimeField('Show Start Time', )
duration = models.DurationField('Duration',)
endtime = models.TimeField('Show End Time (Optional)',blank=True, null=True )
with the starttime and duration I am trying to arrive the endtime while storing the object;
def save(self, *args, **kwargs):
startdelta=timedelta(hours=self.starttime.hour,minutes=self.starttime.minute,seconds=self.starttime.second)
enddelta = startdelta + self.duration
self.endtime = enddelta
super(Showsets, self).save(*args, **kwargs)
Above code throws me error, I want to know how the timefield and duration field works in django also please assist with the ways to query the fields based on starttime or endtime (like objects that starts (starttime) in 30mins from now).
Also curious to know if there are any django-app(add-ons) for time based querying.
Thanks a ton!
Not sure if this will be a good solution for your circumstance but I normally do something like:
start_time = models.TimeField()
end_time = models.TimeField()
def duration(self):
return self.end_time - self.start_time
It seems like a much more concise solution than storing start time with duration and then calculating the end_time on save().
You can combine starttime with today's date and add duration:
from datetime import datetime, date
self.endtime = (datetime.combine(date.today(), self.starttime) + self.duration).time()
I have a piece of code, which is a function called within a loop over a dictionary, it is as follows:
hope = []
seconds = []
hope.append(self.date)
for those in hope:
date = those
pattern = '%m/%d/%Y'
epoch = int(time.mktime(time.strptime(date, pattern)))
seconds.append(epoch)
print seconds
I am getting results like
[1505084400]
[1500850800]
[1509926400]
[1496617200]
[1492383600]
[1488758400]
[1499036400]
[1511136000]
[1511136000]
…
But I want the results of seconds to be like:
[1505084400,1500850800,1509926400,1496617200,1492383600,1488758400,1499036400,1511136000,1511136000.....]
So that the sort and sorted functions will work on it.
Just take the print statement out of the for loop and maintain the state of the lists:
class someclass(object):
def __init__(self):
self.hope = []
self.seconds = []
def appendtoseconds(self):
self.hope.append(self.date)
for those in self.hope:
date = those
pattern = '%m/%d/%Y'
epoch = int(time.mktime(time.strptime(date, pattern)))
self.seconds.append(epoch)
print self.seconds