Python Forum
check log filename with present date
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
check log filename with present date
#1
I'm trying to write a simple check code which reads the log filename (after backup) from a given directory and gives information if log with present date was created or if it wasn't. Code should and with exit = 0 (TRUE) or exit = 2 (FALSE). Log is constructed from name and current date eg. log_2018_08_21) Please, any one may help me with it? I`m not really familiar with coding yet :/

import datetime
import pathlib
import sys

filename = pathlib.Path("backup_" + datetime.datetime.now() + ".log")
if filename.exists ():
    print ("File exist")
	sys.exit(0);
else:
    print ("File not exist")
	sys.exit(2);
Reply
#2
Python is a very strong typed language.
You can't add a DateTime-Object together with a string, because they are different data types.

The use of the builtin function str, returns a string of an object. The object itself know how to make the string.
With datetime you have more than one possible solution:
  • Converting dt-object with str()
  • Use the method strftime datetime.datetime.strftime Python strftime reference
  • Use of format method:
    '{:%Y-%m-%d-%H-%M-%S}'.format(datetime.datetime.now())
  • Use of the isoformat method of the datetime object
    datetime.datetime.now().isoformat()

The straight forward solution:
path = str(datetime.datetime.now()) + "_backup.log"
Example with format method. The curly braces are the placeholder. Everything inside the curly braces, after the colon is the format itself. The datetime object supports this.

path_fmt = "backup_{:%Y-%m-%d-%H-%M-%S}.log"
path = path_fmt.format(datetime.datetime.now())
If you're using linux, try to prevent the use of colons in a path.
A colon is a delimiter and sometimes missinterpreted in shell scripts.

Another trick is, to put the date in front of the path. Then the lexical sorting is equal to the order of date.
This helps if you have a directory full of logfiles.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#3
Thank you very much for your help and tips but still i`m getting an error:/
My code is:

import datetime
import pathlib
import sys
import os

os.path.abspath("C:/Test/")

filename = "backup_{:%Y-%m-%d-%H-%M-%S}.log"
path = filename.format(datetime.datetime.now())

if filename.exists():
    print("File exist")
    sys.exit(0);
else:
    print("File not exist")
    sys.exit(2);
Error:
Error:
Traceback (most recent call last): File "XXX", line 11, in <module> if filename.exists(): AttributeError: 'str' object has no attribute 'exists' Process finished with exit code 1
Reply
#4
As far as I know, Python does not have a function named exists (if you made it up, how do you think it will work). But a Google for "python file name exists" will turn up at least 2 ways to do this. Note also that you should always supply the /complete/path/and/filename as the file may or may not be in the path that Python searches, but the complete path will always work.
Reply
#5
Thanks for suggestions. This code did the trick...
Quote:filename = "backup_{:%Y_%m_%d}.log".format(datetime.datetime.now())
file = open(filename)
Now i`m getting strange error. file = open(filename) FileNotFoundError: [Errno 2] No such file or directory: 'backup_2018_08_22.log' but i have file backup_2018_08_22.log in C:\Test... Below is the code. One more question this script should be working on Ubuntu and there paths are slighty different.
#!/usr/bin/python
  import datetime
  import sys
  import os

os.path.abspath("C:\Test")
filename = "backup_{:%Y_%m_%d}.log".format(datetime.datetime.now())
file = open(filename)

if file.exists():
    print("File exist")
    sys.exit(0);
else:
    print("File not exist")
    sys.exit(2);
Reply
#6
Ive modified the script and now its working. Case closed :)
from pathlib import Path
import sys
import datetime
my_file = Path("C:/Test/backup_{:%Y_%m_%d}.log".format(datetime.datetime.now()))
if my_file.is_file():
    print("Found it")
    sys.exit(0)

else:
    print("Can`t find it")
    sys.exit(2)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Compare current date on calendar with date format file name Fioravanti 1 243 Mar-26-2024, 08:23 AM
Last Post: Pedroski55
  Python date format changes to date & time 1418 4 618 Jan-20-2024, 04:45 AM
Last Post: 1418
  Check if a value is present in each group Menthix 8 2,746 May-16-2022, 12:25 PM
Last Post: Menthix
  Anaconda pip install mpyc Error pip-script.py is not present Anldra12 2 7,859 Dec-13-2021, 06:59 PM
Last Post: Anldra12
  Date format and past date check function Turtle 5 4,272 Oct-22-2021, 09:45 PM
Last Post: deanhystad
  How to add previous date infront of every unique customer id's invoice date ur_enegmatic 1 2,240 Feb-06-2021, 10:48 PM
Last Post: eddywinch82
  How to add date and years(integer) to get a date NG0824 4 2,880 Sep-03-2020, 02:25 PM
Last Post: NG0824
  Date and time as filename Herbert58 3 7,043 Aug-08-2020, 10:11 AM
Last Post: Herbert58
  No Scripts File present after python installation ag2207 5 4,924 Jul-30-2020, 11:11 AM
Last Post: buran
  Python function executes twice when region loop is present bluethundr 2 2,633 Jan-07-2020, 03:01 PM
Last Post: bluethundr

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020