I am writing some data to a .txt file. I am using Open[] to create the text file in the directory I want and then Write[] and WriteString[]. (I am using FileNameJoin[] to create the actual filenames). I tried this out using a test file, called test.txt (and stored in the appropriate directory), it opens, writes to, and closes the file how I want. However, every time the notebook is run, I want to create a new output .txt file, so the files are named based on the date and time (in 24 hours), so part of the filename looks like HH:MM:SS. So, I am running something that looks like:

filename = 
  FileNameJoin[{"C:", "Users", "Me", "Dir1", "Dir2", 

Mathematica gives this error:

OpenWrite::noopen: Cannot open C:\Users\Me\Dir1\Dir2\2019-07-0810:59:01.txt.

I think what it doesn't like is the colons, since if I replace : with ; it opens/creates the file just fine (and it can open a file with just the date as the name). However, this is kind of ugly, and I would really prefer to use : instead.

Any suggestions are appreciated! Thanks you guys!

  • 2
    $\begingroup$ Personally, I solve this problem be replacing XX : YY : ZZ by XXhYYmZZs in the name of the file. Here is the code : StringReplace[DateString[], h : (_ ~~ _) ~~ ":" ~~ m : (_ ~~ _) ~~ ":" ~~ s : (_ ~~ _) :> h ~~ "h" ~~ m ~~ "m" ~~ s ~~ "s"]. It solves a second problem too : sometimes (depending on the operating system) the seconds have decimals (10.45 for instance) $\endgroup$
    – andre314
    Jul 8 '19 at 18:45
  • 1
    $\begingroup$ If you really want to put colons in file names, I suggest you use Linux. However, even there, I think they are better avoided. $\endgroup$
    – mikado
    Jul 8 '19 at 19:24
  • $\begingroup$ Using the StringReplace info from @andre314, you might also consider using DateString["ISODateTime"] such as this: StringReplace[DateString["ISODateTime"], h : (_ ~~ ) ~~ ":" ~~ m : ( ~~ ) ~~ ":" ~~ s : ( ~~ _) :> h ~~ "h" ~~ m ~~ "m" ~~ s ~~ "s"] The result is a more compact representation. $\endgroup$
    – Mark R
    Jul 9 '19 at 0:45

This is not possible. A colon is not a valid character in a file name on Windows.

Reference: https://docs.microsoft.com/en-us/windows/win32/msi/filename

  • $\begingroup$ You're right @Szabolcs, thanks! I am just so used to Linux. $\endgroup$ Jul 8 '19 at 20:18
  • $\begingroup$ Even if valid, it would be prone to all sort of problems. I would avoid spaces, most symbols and long strings in filenames as much as possible. $\endgroup$
    – rhermans
    Jul 9 '19 at 13:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.