在Python中验证文件路径



我有这个代码,用户必须输入一个文件的名称,其中包括一条消息和一个文件的名称,其中消息必须在通过凯撒密码加密后写入。

我想验证输入,这样如果有一个错误的输入,代码不会崩溃,而是要求用户输入一个有效的文件路径,直到用户输入它。我对使用while循环的验证有一些熟悉,但是我不能在不破坏代码其他部分的情况下在这里应用它。

欢迎提出任何建议。

def open_file(source_path: str, dest_path: str):
with open(source_path, mode='r') as fd:
while line := fd.readline():
return line

def write_to_file(dest_path: str, line: str):
with open(dest_path, mode='a') as fd:
fd.write(line)

source_path = input("Enter the name of the file including the message: ")
dest_path = input("Enter the name of the file where the encrypted message will be written: ")

MODE_ENCRYPT = 1

def caesar(source: str, dest: str, steps, mode):
alphabet = "abcdefghijklmnopqrstuvwxyzabcABCDEFGHIJKLMNOPQRSTUVWXYZABC"
alpha_len: int = len(alphabet)
new_data = ""
file = open_file(source_path, dest_path)
for char in file:
index = alphabet.find(char)
if index == -1:
new_data += char
else:
# compute first parth
changed = index + steps if mode == MODE_ENCRYPT else index - steps
# make an offset
changed %= alpha_len
new_data += alphabet[changed:changed + 1]
write_to_file(dest_path, new_data)
return new_data

while True:
#  Validating input key
key = input("Enter the key: ")
try:
key = int(key)
except ValueError:
print("Please enter a valid key: ")
continue
break
ciphered = caesar(source_path, dest_path, key, MODE_ENCRYPT)

不太确定不能使用while循环是什么意思,但是这里有一个使用pathlib检查路径是否存在的简单方法。

from pathlib import Path
while True:
source_path = Path(input("Enter the name of the file including the message: "))
if source_path.exists():
break
print("Please input a valid path")
while True:
dest_path = Path(input("Enter the name of the file where the encrypted message will be written: "))
if dest_path.exists():
break
print("Please input a valid path")

您可以使用Python内置的OS模块。以下是路径为有效路径之前的代码。

Note:检查MAXIMUM RETRIES将帮助代码避免陷入用户的无限循环。

import os
def getPath():
MAXIMUM_RETRIES = 5
count = 0
file_path = ""
while True:
count += 1
file_path = input("Enter the path: ")
if os.path.exists(file_path):
break
if count >= MAXIMUM_RETRIES:
print("You have reached maximum number or re-tries. Exiting...")
exit(1)
print("Invalid Path. Try again.")
return file_path

相关内容

  • 没有找到相关文章

最新更新