I was wondering how to use the os.path and pathlib correctly. I'm supposed to search for a directory(which I already did) and then after that enter a letter and space and it will decide what it will do.
import os import os.path import shutil from pathlib import Path
def search_files():
directory = input()
exist = Path(directory)
if exist.exists():
return directory
else:
print("Error")
print("Try again: ")
return search_files()
def search_characteristics(directory):
interesting = input()
exist = os.path.exists(directory)
if interesting[0] == 'N':
return os.path.join(directory, interesting)
else:
print("Error")
return search_characteristics()
if __name__ == '__main__':
directory = input()
search_files()
search_characteristics(directory)
For this as you can see, search_files looks for a directory which works. The next part is the one where I'm confused. Basically after it searches for a directory, C:\\Program Files or something, I would enter N in the new line to search for what I want in the directory.
Say like
C:\\Users\\Desktop\\stuff
N something.txt
The N would look for the exact name of the file.
Am I doing it correctly or is there another way to do it?
This script will do what you want. Along with using the result of your directory search function for the next call, I also changed the compare to use .startswith
so that a emtpy string response doesn't crash the program.
import os
from pathlib import *
def search_files():
directory = input()
exist = Path(directory)
if exist.exists():
return directory
else:
print("Error")
print("Try again: ")
return search_files()
def search_characteristics(directory):
interesting = input()
exist = os.path.exists(directory)
if interesting.startswith('N'):
return os.path.join(directory, interesting)
else:
print("Error")
return search_characteristics(directory)
if __name__ == '__main__':
directory = search_files()
fn = search_characteristics(directory)
print(fn)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.