'Python os.path.join not creating a .txt file

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.



Solution 1:[1]

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")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ramprakash