DEV Community

ABUL HASAN A
ABUL HASAN A

Posted on

TASK - 7

1 a) import os
from datetime import datetime

def create_text_file_with_timestamp():
# Get the current timestamp
timestamp = datetime.now().strftime("%Y%m%d%H%M%S")

# Create a file name with the timestamp
file_name = f"text_file_{timestamp}.txt"

Create and write content to the file

with open(file_name, 'w') as file:
file.write("This is a text file created with the current timestamp.")

print(f"Text file '{file_name}' created successfully.")

Enter fullscreen mode Exit fullscreen mode




Call the function to create the text file

create_text_file_with_timestamp()
b) from datetime import datetime

def create_text_file_with_timestamp():
# Get the current timestamp
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

# Create a file name with the timestamp
file_name = f"text_file_{timestamp}.txt"

Create and write content to the file

with open(file_name, 'w') as file:
file.write(f"This file was created at: {timestamp}")

print(f"Text file '{file_name}' created successfully.")

Enter fullscreen mode Exit fullscreen mode




Call the function to create the text file

create_text_file_with_timestamp()
2 ) def read_text_file(file_name):
try:
# Open the file in read mode
with open(file_name, 'r') as file:
# Read the content of the file
content = file.read()

        # Display the content in the console
print(f"Content of '{file_name}':\n{content}")
except FileNotFoundError:
print(f"Error: File '{file_name}' not found.")
except Exception as e:
print(f"Error: An unexpected error occurred - {e}")
Enter fullscreen mode Exit fullscreen mode




Example usage:

file_to_read = "text_file_20231203120000.txt" # Replace with the actual file name
read_text_file(file_to_read)

Top comments (0)