-2

I am trying to run this script so that it creates a .txt file based on the date.

#Importing libraries
import os
import sys

#Selecting time and methods
from time import gmtime, strftime
from datetime import datetime

#Fortmatting date & printing it
date = datetime.now().strftime("%Y_%m_%d-%I:%M_%p")

#Creating the name of the file, plus the date we created above
newFile = ("Summary_" + date) + '.txt'

#Creating the filepath where we want to save this file
filepath = os.path.join('C:\\Users\\myUser\\Desktop\\myFolder', newFile)

#If the path doesn't exist
if not os.path.exists('C:\\Users\\myUser\\Desktop\\myFolder'):
    os.makedirs('C:\\Users\\MyUser\\Desktop\\myFolder')
f = open(filepath, "w")

Everything works, however, the file gets created as a File and not a .txt file. I am not sure if I am not concatenating the strings correctly, or if there is an additional step I need to take.

I noticed that if I type anything after the date string, it doesn't get added to the end of the file.

If I type the string manually like this, then it works just fine:

filepath = os.path.join('C:\\Users\\myUser\\Desktop\\myFolder', "Summary_DateGoesHere.txt")

Am I missing something in my script? I appreciate the assistance.

Cardanos
  • 3
  • 2
  • 1
    How do you know? Remember that Windows Explorer, by default, hides the extension from you. – Tim Roberts May 05 '22 at 05:09
  • Do you get the expected output if you remove the colon in the `date` variable? [Colons are illegal characters for Windows file names](https://stackoverflow.com/questions/1976007/what-characters-are-forbidden-in-windows-and-linux-directory-names). – Taren Sanders May 05 '22 at 05:14
  • @TimRoberts when I check the file under properties it just shows up as a File and not a .txt file. If I manually type the file name without passing the variable (i.e: “myfile.txt”), it saves just fine so I don’t understand why when I use the variable it won’t work. Hopefully this helps clarify my issue. Thank you for looking into it. – Cardanos May 05 '22 at 05:54
  • Re "_I am not sure if I am not concatenating the strings correctly_". So did you try to `print(newFile)` after the string concatenation? Did you `print(filepath)`? What are the results? If you manually type the same string, does it work then? – wovano May 05 '22 at 06:15

1 Answers1

2

The issue here is , Windows won't allow to create a file name having colon :

Here, your filename variable is - "Summary_2022_05_05-11:24_AM.txt". As colon is not allowed, its truncating after 11, and creating a file name with just Summary_2022_05_05-11.

To fix this, you can use underscore or hyphen before minutes field like this:

date = datetime.now().strftime("%Y_%m_%d-%I_%M_%p")
Ramprakash
  • 151
  • 1
  • 8