Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
OSERROR When mkdir
#1
Error:
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'D:\\1. Oshadha\\2. Code\\Python\\11. Discord Bot\\Logs\\1 Session 22/06/29 - 10:34:05.txt'
def time_now():
    t = datetime.datetime.now()
    frmt = t.strftime('%y/%m/%d - %H:%M:%S')
    return frmt

current_Dir = os.getcwd()
log_Dir = os.path.join(current_Dir + "\\Logs\\")

cSession = f'{log_Dir}{ID} Session {time_now()}.txt'
os.mkdir(cSession)
Whats wrong??


EDIT: I got it, Invalid File Name. Cant use special Characters.
Im Dumb..
Reply
#2
try

log_Dir = os.path.join(current_Dir, "Logs")

you will create a directory with extension .txt ?
Reply
#3
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().
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#4
For creating folder with subfolder you can use makedirs

os.makedirs('folder/subfolder/')
Reply
#5
The pathlib-Object can do this also: https://docs.python.org/3/library/pathli...Path.mkdir
Quote:Path.mkdir(mode=0o777, parents=False, exist_ok=False)¶

Create a new directory at this given path. If mode is given, it is combined with the process’ umask value to determine the file mode and access flags. If the path already exists, FileExistsError is raised.

If parents is true, any missing parents of this path are created as needed; they are created with the default permissions without taking mode into account (mimicking the POSIX mkdir -p command).
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  OSError occurs in Linux. anna17 2 318 Mar-23-2024, 10:00 PM
Last Post: snippsat
  directory not being created after os.mkdir() CAD79 3 381 Mar-16-2024, 04:00 PM
Last Post: deanhystad
  OSError with SMPT script Milan 0 786 Apr-28-2023, 01:34 PM
Last Post: Milan
  OSError: Unable to load libjvm when connecting to hdfs with pyarrow 3.0.0 aupres 0 3,177 Mar-22-2021, 10:25 AM
Last Post: aupres
  pyarrow throws oserror winerror 193 1 is not a valid win32 application aupres 2 3,797 Oct-21-2020, 01:04 AM
Last Post: aupres
  Python Paramiko mkdir command overwriting existing folder. How can i stop that? therenaydin 1 3,235 Aug-02-2020, 11:13 PM
Last Post: therenaydin
  OSError: [Errno 26] Text file busy: '/var/tmp/tmp5qbeydbp batchenr 1 4,231 Mar-20-2020, 01:58 PM
Last Post: ibreeden
  Multiprocessing OSError 'too many open files' DreamingInsanity 3 10,387 Dec-27-2019, 04:50 PM
Last Post: DreamingInsanity
  .py to exe error "oserror winerror 193" michael1789 3 4,899 Dec-03-2019, 05:49 AM
Last Post: michael1789
  OSError: [Errno 13] Permission denied Kolterdyx 3 17,891 Sep-07-2018, 11:01 AM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

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