TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to PYTHON

Python Filename With Date Example (date.today)

Use date.today to place the current date in a file name. Write lines to the current date file.
Filename, date. Suppose you have a program that should be run every day. It performs some important computational task or records some data and writes a log file.
With the current date, we can generate a unique file name each day. And later, these files can be sorted and accessed by the date. This is convenient.File
Example program. Here is an example program. We introduce the get_filename_datetime method. We import the datetime module. In the method, we concatenate a file name based on date.today.

Note: We use the txt extension, but this can be easily changed. We must convert the date.today() result into a string with str.

Python program that uses date.today for file names from datetime import date def get_filename_datetime(): # Use current date to get a text file name. return "file-" + str(date.today()) + ".txt" # Get full path for writing. name = get_filename_datetime() print("NAME", name) path = "C:\\programs\\" + name print("PATH", path); with open(path, "w") as f: # Write data to file. f.write("HELLO\n") f.write("WORLD\n") Output NAME file-2017-05-17.txt PATH C:\programs\file-2017-05-17.txt Contents (file): HELLO WORLD
Notes, NAME and PATH. The get_filename_datetime method returns the file name only. So we must concatenate the path to the file (in the logging directory) before using it in open().

Note: Please modify the path to one that is relevant for your system. Also, a raw string literal can be used.

String Literals
A summary. A random file name can be used, but this is confusing to access later. With a date in the file name, a human can easily access the desired logging data.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf