0% found this document useful (0 votes)
110 views

Writing and Reading Files in Os

The document contains 3 functions - file_date, new_directory, and parent_directory. file_date takes a filename as input and returns the creation date as a string in yyyy-mm-dd format. new_directory creates a new directory if it doesn't exist, makes a file within it, and returns the contents of the new directory. parent_directory returns the absolute path of the parent directory of the current working directory.

Uploaded by

swarnim verma
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
110 views

Writing and Reading Files in Os

The document contains 3 functions - file_date, new_directory, and parent_directory. file_date takes a filename as input and returns the creation date as a string in yyyy-mm-dd format. new_directory creates a new directory if it doesn't exist, makes a file within it, and returns the contents of the new directory. parent_directory returns the absolute path of the parent directory of the current working directory.

Uploaded by

swarnim verma
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

import os

import datetime

def file_date(filename):
# Create the file in the current directory
with open (filename,'w') as file:
pass
timestamp = os.path.getmtime(filename)
c=datetime.datetime.fromtimestamp(timestamp)
# Convert the timestamp into a readable format, then into a string

# Return just the date portion


# Hint: how many characters are in “yyyy-mm-dd”?
return ("{}".format(c.strftime("%Y-%m-%d")))

print(file_date("newfile.txt"))
# Should be today's date in the format of yyyy-mm-dd

import os
def new_directory(directory, filename):
# Before creating a new directory, check to see if it already exists
if os.path.isdir(directory) == False:
os.mkdir(directory)

# Create the new file inside of the new directory


os.chdir(directory)
with open (filename, "w") as file:
pass
os.chdir("..")
# Return the list of files in the new directory
return os.listdir(directory)

print(new_directory("PythonPrograms", "script.py"))

import os
def parent_directory():

# Create a relative path to the parent


# of the current working directory
relative_parent = os.path.join(os.getcwd(), os.pardir)
# Return the absolute path of the parent directory
return os.path.abspath(relative_parent)

print(parent_directory())

You might also like