繁体   English   中英

验证 Python 中的文件路径

[英]Validating file paths in 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM