Python Forum

Full Version: check log filename with present date
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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);
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.
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
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.
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);
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)