0

I'll try to describe the problem in a simple way.

I have a .txt file that I can not know the full name of it which located under constant path

[for example: the full name is: Hello_stack.txt, I only can give to function the part: 'Hello_']

the input is: Path_to_file/ + 'Hello_' the expected output is: Path_to_file/Hello_stack.txt

How can i do that?

I tried to give a path and check recursively if part of my file name is exist and if so, to return it's path.

this is my implementation: [of course I'd like to get another way if it works]


def get_CS_R2M_METRO_CALLBACK_FILE_PATH():
    directory = 'path_of_file'
    file_name = directory + 'part_of_file_name'
    const_path = Path(file_name)
    for path in [p for p in const_path.rglob("*")]:
        if path.is_file():
            return path
        

Thanks for help.

0

1 Answer 1

1

You might retrieve the file list in your path and then select from the list based upon your partial file name. Here is a snippet of code to perform that type of function on a Linux machine.

import os

dir = '/home/craig/Python_Programs/GetFile'


files = os.listdir(dir)

print('Files--> ', files)

for i in files:
    myfile = 'Hello_'
    if (myfile[0:4] == i[0:4]):
        print('File(s) like \"Hello_\"-->', i)

When I executed this simple program over a directory/folder that had various files in the directory, here was the output to the terminal.

Una:~/Python_Programs/GetFile$ python3 GetFile.py 
Files-->  ['Hello_Stack.txt', 'Okay.txt', 'Hi_Stack.txt', 'GetFile.py', 'Hello_Stack.bak']
File(s) like "Hello_"--> Hello_Stack.txt
File(s) like "Hello_"--> Hello_Stack.bak

The literal value for your path would be different on a Windows machine. I hope this might provide you with a method to achieve your goal.

Regards.

Sign up to request clarification or add additional context in comments.

1 Comment

That actually worked perfectly on first try. thank you so much!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.