-1

I don't think that the following code is efficient enough to search for a filename in the current directory. The filename will be stored as a string, so will python be able to search a 'filename' string from the directories that are non-string?

filename = input("What would you like to name the File? ")
import os
if f"{filename}.txt" in os.getcwd():
    print(True)
  • `os.getcwd()` will only return your the current working directory path. What you want to do is to get all the file names in the current and its subdirectories and then match the file name with the list. Check this answer on how to read the files names: https://stackoverflow.com/a/2909998/13961165 – LeelaPrasad Dec 28 '20 at 12:21

3 Answers3

0

os.getcwd() returns the name of the directory itself, not a list of files (see https://www.tutorialspoint.com/python/os_getcwd.htm)

You want to try something like:

import os
for file in os.listdir("/mydir"):
    if file == f"{filename}.txt:
        print("File Found")
Retro
  • 130
  • 16
0

Also, you need to try-except statement for this code snippet. Otherwise, at the wrong file, the app will be crashed.

Kenly
  • 24,317
  • 7
  • 44
  • 60
0
import os 
# Getting current folder path
cmd = os.getcwd()
    # getting file name from user
    file_name = input('Enter file name to be search : ')
    #Looping through all folder and files in the current directory
    for file in os.listdir(cmd):
        # compare the file name user entered with file names from current 
        # directory file name
        if file == f"{file_name}.txt":
            print("File Found")
Jake
  • 1
  • 1