目标是能够在用户调用时读取文件。我已经成功地实现了这一步骤;用户调用程序读取文件的内容,程序将其打印出来。然而,我被困在错误恢复上。
如果用户输入了一个不存在的文件名,程序应该提示用户该文件名不存在,并要求用户再次输入。
程序使用os
库,我使用os.getcwd()
来列出可查看的文件。我想,既然它列出了它,我可以把它设置为一个列表,它会做两件事之一——匹配=打印文件的内容;无匹配=打印错误。我没能成功地做到这一点。
还有其他更好的方法吗?或者列表的想法是可行的吗?
这是我的代码,在列表之前的想法。我省略了运行代码不需要的部分:
import os, os.path
QUIT = '8'
COMMANDS = ('1', '2', '3', '4', '5', '6', '7', '8')
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):
if command == '7':
viewFile()
def viewFile():
#print files in cwd
listCurrentDir(os.getcwd())
fname = input("Enter Filename: ")
with open(fname, 'r') as f:
contents = f.read()
print(contents, "n")
def listCurrentDir(dirName):
"""Prints a list of the cwd's contents."""
lyst = os.listdir(dirName)
for element in lyst: print(element)
if __name__ == "__main__":
main()
这是我的代码,在我尝试实现列表后的想法:
def viewFile():
fileList = []
fileList = listCurrentDir(os.getcwd())
fname = input("Enter Filename: ")
if fname not in fileList:
print("Error: Filename does not exist.")
break
else:
with open(fname, 'r') as f:
contents = f.read()
print(contents, "n")
我想放弃os
模块,选择pathlib
,这是一个更现代、更高级的模块,用于执行路径/目录/文件操作,是标准库的一部分:
def view_file(): # Prefer snake_case in Python
from pathlib import Path
file_name = input("Enter filename:")
if not (abs_path:=Path.cwd() / file_name).exists() or not abs_path.is_file():
print("The specified file "{}" does not exist!".format(abs_path))
return
print("Opening "{}"...".format(abs_path))
print(abs_path.read_text())
话虽如此,您也可以尝试在try-except块中封装一个普通的open
。如果open
引发了FileNotFoundError
异常,那么您就知道找不到该文件。
对于特定的问题,这是答案,使用try和except。
def viewFile():
listCurrentDir(os.getcwd())
while True:
fname = input("Enter Filename: ")
try:
with open(fname, 'r') as f:
contents = f.read()
print(contents, "n")
break
except FileNotFoundError:
print("Error: File name does not exist. nPlease try again.")
continue
您可以使用glob:
import traceback
import glob
def viewFile():
fileList = glob.glob("*")
fname = input("Enter Filename:")
if fname not in fileList:
print("Error: Filename does not exist.")
return
elif not os.path.isfile(fname):
print("Error: Not a file.")
return
else:
try:
with open(fname, 'r') as f:
contents = f.read()
print(contents, "n")
except:
print("Error while reading the file:")
print(traceback.format_exc())
glob的神奇之处在于,您可以使用regex以及它的绝对路径和相对路径,这样您就可以做到:
fileList = listCurrentDir(glob.glob("*.txt"))
或:
fileList = listCurrentDir(glob.glob("/home/Frankie/*.txt"))