Your filename is illegal. It could work on any Operating System, because of the forward slashes in the file name.
A bit of history, why Windows uses Backslashes:
https://www.howtogeek.com/181774/why-win...d-slashes/
You can't use a forward slash inside a
Directory
name or
File
name.
If you want to sort the filenames by date, then you should use ISO8601 format, which is also convenient for lexicographic order.
https://en.wikipedia.org/wiki/Filename
Quote:Used as a path name component separator in Unix-like, Windows, and Amiga systems. (For as long as the SwitChar setting is set to '/ ', the DOS COMMAND.COM shell would consume it as a switch character, but DOS and Windows themselves always accept it as a separator on API level.)
The big solidus ⧸ (Unicode code point U+29F8) is permitted in Windows filenames.
The normal
/
is as different character as
⧸
.
You're using the normal forward slash, which is not allowed in file names.
The
ISO8601
has also colons inside. They are allowed on Windows, but if you like, you can replace them with a dash or minus.
The alternative is, that you use the
strftime
method on the
datetime
object.
From Wikipedia:
Quote:The letter colon ꞉ (U+A789) and the ratio symbol ∶ (U+2236) are permitted in Windows filenames. In the Segoe UI font, used in Windows Explorer, the glyphs for the colon and the letter colon are identical.
For easier handling of
Paths
you should look what
pathlib is.
from datetime import datetime as DateTime
# renamed datetime class to DateTime
# DateTime is a class
from pathlib import Path
def make_path(session_id):
# with colons
# now_iso = DateTime.now().replace(microsecond=0).isoformat()
# colons replaced by _
now_iso = DateTime.now().replace(microsecond=0).isoformat().replace(":", "_")
session = Path("Logs").joinpath(f"{session_id}-{now_iso}.txt")
# here the directory is created and if it exists, it's also ok
session.parent.mkdir(exist_ok=True)
return session
# make_path takes the session_id
path_to_session_logfile = make_path(1337)
print("Current Logfile", path_to_session_logfile)
print("Parent", path_to_session_logfile.parent)
print("Parent Absolute", path_to_session_logfile.parent.absolute())
Output:
Current Logfile Logs/1337-2022-06-29T10_39_20.txt
Parent Logs
Parent Absolute /home/andre/Logs
As you can see, it also works on Linux. The same code should do the same on Windows, Mac or Android.
The
pathlib
is a big help to make code more interoperable between the different Operating Systems.
If you have a Path object, which points to a relative Path, you can also create from this an absolute Path.
Then the current working directory is used, to construct the absolute Path, so no need to call
os.getcwd()
.