Add a command to this chapter’s case study program (in the file filesys.py) that allows the user to view the contents of a file in the current working directory. When the command is selected, the program should call the function viewFile to display a list of filenames and a prompt for the name of the file o be viewed. Be sure to include error recovery. (LO: 7.1)
Instructions
Task 1: Define the viewFile function.
An example of the program is below:
1 List the current directory
2 Move up
3 Move down
4 Number of files in the directory
5 Size of the directory in bytes
6 Search for a file name
7 View the contents of a file
8 Quit the program
Enter a number: 1
filesys.py
text1.txt
text2.txt
1 List the current directory
2 Move up
3 Move down
4 Number of files in the directory
5 Size of the directory in bytes
6 Search for a file name
7 View the contents of a file
8 Quit the program
Enter a number: 7
Files in pathtofiles:
filesys.py
text1.txt
text2.txt
Enter a file name from these names: text1.txt
The quick brown fox jumps over the lazy dog. This sentence is an example of a simple and straightforward sentence. It contains short words and has a clear structure. On the other hand, the intricacies
of the English language can lead to more complex and challenging texts. Reading comprehension and text analysis are important skills for individuals of all ages and backgrounds.
RUN CODE
CALCULATE GRADE
SUBMIT
import os, os.path
QUIT = '8'
COMMANDS = ('1', '2', '3', '4', '5', '6', '7')
MENU = """1 List the current directory
2 Move up
3 Move down
4 Number of files in the directory
5 Size of the directory in bytes
6 Search for a file name
7 View the contents of a file
8 Quit the program"""
def main():
while True:
print(os.getcwd())
print(MENU)
command = acceptCommand()
runCommand(command)
if command == QUIT:
print("Have a nice day!")
break
def acceptCommand():
"""Inputs and returns a legitimate command number."""
while True:
command = input("Enter a number: ")
if not command in COMMANDS:
print("Error: command not recognized")
else:
return command
def runCommand(command):
"""Selects and runs a command."""
if command == '1':
listCurrentDir(os.getcwd())
elif command == '2':
moveUp()
elif command == '3':
moveDown(os.getcwd())
elif command == '4':
print("The total number of files is",
countFiles(os.getcwd()))
elif command == '5':
print("The total number of bytes is",
countBytes(os.getcwd()))
elif command == '6':
target = input("Enter the search string: ")
fileList = findFiles(target, os.getcwd())
if not fileList:
print("String not found")
else:
for f in fileList:
print(f)
elif command=='7':
target=input("Enter a file name from these names: ")
def listCurrentDir(dirName):
"""Prints a list of the cwd's contents."""
lyst = os.listdir(dirName)
for element in lyst: print(element)
def moveUp():
"""Moves up to the parent directory."""
os.chdir("..")
def moveDown(currentDir):
"""Moves down to the named subdirectory if it exists."""
newDir = input("Enter the directory name: ")
if os.path.exists(currentDir + os.sep + newDir) and
os.path.isdir(newDir):
os.chdir(newDir)
else:
print("ERROR: no such name")
def countFiles(path):
"""Returns the number of files in the cwd and
all its subdirectories."""
count = 0
lyst = os.listdir(path)
for element in lyst:
if os.path.isfile(element):
count += 1
else:
os.chdir(element)
count += countFiles(os.getcwd())
os.chdir("..")
return count
def countBytes(path):
"""Returns the number of bytes in the cwd and
all its subdirectories."""
count = 0
lyst = os.listdir(path)
for element in lyst:
if os.path.isfile(element):
count += os.path.getsize(element)
else:
os.chdir(element)
count += countBytes(os.getcwd())
os.chdir("..")
return count
def findFiles(target, path):
"""Returns a list of the file names that contain
the target string in the cwd and all its subdirectories."""
files = []
lyst = os.listdir(path)
for element in lyst:
if os.path.isfile(element):
if target in element:
files.append(path + os.sep + element)
else:
os.chdir(element)
files.extend(findFiles(target, os.getcwd()))
os.chdir("..")
return files
def viewFile():
"""
Display a list of filenames in the current
working directory and prompt the user to enter a
filename to view.
"""
#Get a list of files in the current working directory
files=os.listdir()
#Display the list of filenames
print("Files in the current working directory: ")
for filename in files:
print(filename)
#Prompt the user to enter a filename
input=input("Enter the name of the file you want to view: ")
#Check if the entered filename exists
if input in files:
#Read and display the contents fo the file
with open(input,'r') as file:
print ("nFile contents: ")
print(file.read())
else:
print(f"Error:file'{input}'doesn't exist in the current working directory.")
except Exception as e:
print (f"An error occurred: {e}")
if __name__ == "__main__":
main ()
Charity is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1