0

I had created a python program that asks a user to create a file (for simplicity this will just be a .txt file). The stipulation is that the file can only contain alphabets and an "_". No leading numbers and cannot contain special characters and it must contain an "." somehow for an extension. In this program I did use a regex to find a pattern for a valid file format. But here is my problem. The problem is the while logic. I don't know how to fix this problem on how if there is something wrong with the file name it will flag it and keep asking for the right one. Can anyone help me with the logic here? Thanks. Here is my code

import re

def file_creation(user_files):
with open(user_files,"w+") as f:
    f.writelines(f'This is what is entered into the file {user_files}\n')
    f.writelines('======================================' + '\n')
    f.writelines(input('Please enter a sentence: ') + '\n')
    ask = input('Do you want to add more lines: ').lower().strip()
    while ask != 'n':
        f.writelines(input('Please enter a sentence: ') + '\n')
        ask = input('Do you want to add more lines: ').lower().strip()
        if ask == 'n':
            f.writelines(f'======================================' + '\n')
            f.writelines('Thanks for playing!' + '\n')
            f.close()
            m = open(user_files,"r+")
            print(m)
            
if __name__ == "__main__":
    user_files = input('Please enter a valid file: ')
    pattern1 = re.compile('[ @ ! # $ % ^ & * ( ) < > ? / \ | { } ~ : ]')
    while pattern1.search(user_files) is not None:
        print(f'Filename can only contain an alphabet, numbers, and _.')
        user_files = input('Please enter a valid file: ')
    while re.search("^\d",user_files) is not None:
        print(f'Filename only can start with an alphabet or _.')
        user_files = input('Please enter a valid file: ')
    while re.search("\.",user_files) is None:
        print('Filename needs to have an extension')
        user_files = input('Please enter a valid file: ')
    

 print(f'{user_files} is a valid filename.')
 file_creation(user_files)

Output should be:

Please enter a filename: abc
File name needs to have an extension.
Please enter a proper filename: abc.4#r
Filename can contain only Alphabets, digits and "_".
Please enter a proper filename: 23ab.exe
Filename only can start with Alphabets or '_'.
Please enter a proper filename: abc#$.txt
Filename can contain only Alphabets, digits and "_".
Please enter a proper filename: abc@#abc.txt
Filename can contain only Alphabets, digits and "_".
Please enter a proper filename: Test1.txt
Please enter a sentence: This is the first line.
Do you want to add more lines? (Y/N) y
Please enter a sentence: This is the second line.
Do you want to add more lines? (Y/N) n

This is what's entered into file Test1.txt.
=============================
This is the first line.
This is the second line.
=============================
Do you want to create another file? (Y/N) y
Let's create another file.
Please enter a filename: 3ab.doc
Filename only can start with Alphabets or '_'.
Please enter a proper filename: Test.doc
Please enter a sentence: Test.doc the first line.
Do you want to add more lines? (Y/N) y
Please enter a sentence: Test.doc !@#$%&*()
Do you want to add more lines? (Y/N) y
Please enter a sentence: Test.doe the third line.
Do you want to add more lines? (Y/N) n

This is what's entered into file Test.doc.
=============================
Test.doc the first line.
Test.doc !@#$%&*()
Test.doe the third line.
=============================
Do you want to create another file? (Y/N) n
Thank you for playing!

Thanks for all your help.

XeLa
  • 19
  • 1
  • You have 3 while loops checking for filename correctness. I would shrink it to just 1 and checking all the 3 conditions with some boolean logic. – Michalor Oct 20 '22 at 05:44

1 Answers1

0

Put the 3 conditions you have in a while loop using if statements instead to check for all 3. Use continue to go the start of the while loop and ask for new input on invalid input. break out of the loop of if all checks are passed.

import re

pattern1 = re.compile('[ @ ! # $ % ^ & * ( ) < > ? / \ | { } ~ : ]')
while True:
    user_files = input('Please enter a valid file: ')
    if pattern1.search(user_files) is not None:
        print('Filename can only contain an alphabet, numbers, and _.')
        continue
    if re.search("^\d",user_files) is not None:
        print('Filename only can start with an alphabet or _.')
        continue
    if re.search("\.",user_files) is None:
        print('Filename needs to have an extension')
        continue
    break
Tzane
  • 2,752
  • 1
  • 10
  • 21