Files in Python:
Python file handling is a way of saving program output to a file or reading data from a file. File handling is a crucial concept in the programming world. File management is used in almost every form of project. Assume you are constructing an inventory management system. You have data in the inventory management system related to sales and purchases, thus you must save that data somewhere. Using Python’s file management, you can save that data to a file. You must be given data in the form of a comma-separated file or a Microsoft Excel file if you wish to conduct data analysis. Using file handling, you can read data from a file and write output back into it.
Given a file, the task is to create a filename containing the date or time in a given file in python
- Python NumPy loadtxt() Function
- Python Program to Count Number of Digits in a Text File
- Python open() Function with Examples
Program to Create Filename containing Date or Time in Python
Below is the full approach for creating a filename containing the date or time in a given file in python
Approach:
- Import datetime from datetime module using the import keyword.
- Get the current date and time using the datetime.now() function.
- Print the current date and time.
- Pass the above datetime object to str() function to convert it into string and store it in a variable.
- Create the above file object with an extension using the string concatenation.
- Make a single variable to store the path of the file. This is a constant value. This value must be replaced with the file path from your own system in the example below.
- Open the file in write mode. In this case, we’re writing the contents into the file.
- Print the created file name.
- Close the file using the close() function.
- The Exit of Program.
Below is the implementation:
# Import datetime from datetime module using the import keyword from datetime import datetime # Get the current date and time using the datetime.now() function currnt_datetime = datetime.now() # Print the current date and time print("The Current date and time is : ", currnt_datetime) # Pass the above datetime object to str() function to convert it into string and # store it in a variable stringcurrnt_datetime = str(currnt_datetime) # Create the above file object with an extension using the string concatenation filename = stringcurrnt_datetime+".txt" # Make a single variable to store the path of the file. This is a constant value. # This value must be replaced with the file path from your own system in the example below. givenFilename = "samplefile.txt" # Open the file in write mode. In this case, we're writing the contents into the file. gvn_file = open(givenFilename, 'w') # Print the created file name. print("The created File name is: ", gvn_file.name) # Close the file using the close() function gvn_file.close()
Output:
The Current date and time is : 2021-12-28 20:30:05.347396 The created File name is: samplefile.txt