Searching for a file in python

Configurare noua (How To)

Situatie

In this example, you’ll build a file searching tool using the Pathlib module. As a simple implementation, you can use the following code:

Solutie

from pathlib import Path

file_name = input(“Filename: “)
folder = “.”
folder_answer = input(“Folder path (leave empty for the current folder): “)
if folder_answer:
folder = folder_answer

for path in Path(folder).rglob(file_name):
print(path.absolute())
You begin by importing Path from pathlib module. Then, you get the file name to search from user input. You also get the folder in which the search will be performed. In this case, the default value “.” is considered when the user input is empty, which represents the current folder.

Finally, you use the .rglob() method to search for a file name pattern in the folder specified by folder. As rglob() returns a list of path objects, to print all occurrences, you iterate on the list using a for loop. For each item of the list, the absolute path is obtained using the .absolute() method and printed as output.

Try saving the program as find_file.py and perform a search. Note that you can use wildcards when inputting the file name. The output should be like the following:

python find_file.py
Filename: find_file.py
Folder path (leave empty for the current folder):
/home/user/src/find_file.py
Now, add input validation and support for command line arguments with the following code:

from pathlib import Path
import argparse

parser = argparse.ArgumentParser(description=”Find file in file system”)

parser.add_argument(
“file_name”, nargs=”?”, help=”File name (can use wildcards such as *)”,
default=None
)
parser.add_argument(
“folder”, nargs=”?”, help=”Folder (default: current)”,
default=None
)

arguments = parser.parse_args()

use_arguments_file_name = True if arguments.file_name is not None else False
use_arguments_folder = True if arguments.folder is not None else False

# Validation of file name
if use_arguments_file_name:
file_name = arguments.file_name
else:
while True:
file_name = input(“Filename: “)

if file_name == “”:
print(“Invalid file name”)
continue
break

# Processing of the folder argument
folder = “.”
if use_arguments_folder:
folder = arguments.folder
else:
folder_answer = input(“Folder path (leave empty for the current folder): “)
if folder_answer:
folder = folder_answer

for path in Path(folder).rglob(file_name):
print(path.absolute())

Tip solutie

Permanent

Voteaza

(10 din 19 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?