Home > Software engineering >  Validating file paths in Python
Validating file paths in Python

Time:11-23

I have this code where the user has to input the name of a file which includes a message and the name of a file where the message must be written after its encrypted via Caesar-Cipher.

I would like to validate the inputs, so that if there's a wrong input, the code won't crash but ask the user for a valid file path until the user inputs it. I have some familiarity with validation using the while loop, however I couldn't apply it here without ruining other parts of the code.

Any suggestions are appreciated.

  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)

CodePudding user response:

Not quite sure what you meant by not being able to use a while loop, but here is a simple way of checking if the paths exists using 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")

CodePudding user response:

You can use inbuilt OS module in Python. Here is the code until the path is a valid path.

Note: Keeping a check for MAXIMUM RETRIES will help the code to not stuck in an infinite loop for the user.

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
  • Related