Forum Thread: How to Search a Folder for a File in Python?

How to Search a Folder for a File in Python?

Hello everyone, I am trying to make a simple program that asks for something simple (like a name) and uses that input to search a folder for a file with the same name. If such a file doesn't exist, the program will create a file with said name and write in answers to a series of questions.

As of now, the only component the program is missing is a way to search a folder for a specific, named file matching the input value. If anyone could shed some light on this process I would be grateful, as google hasn't been much help. Thanks!

3 Responses

Did you really google it? A quick google search of the exact word-for-word title of this post brings up numerous links that show how to do exactly what you are trying to accomplish.

Check out the os module, which can look through the directory.

Add a try statement and then if no file is found, use the write command to create a new one.

import os #module for operation system commands
filetosearch = rawinput("Type the file path: ")
if(os.path.isfile(file
tosearch)):
---> #code if file is found
else:
----> #code if file is not found

Note that ----> is identation.

Share Your Thoughts

  • Hot
  • Active