简体   繁体   中英

How to get path to file while the name of file is not full in python

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.

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.

Using pathlib.Path make a Path object of the directory. Then use Path.glob with the pattern you are looking for.

from pathlib import Path

path = Path(r'c:\path.to.file')
pattern = 'hello_*.txt'
for p in path.glob(pattern):
    print(p)

To make the pattern dynamic use string formatting .

a = 'hello_'
pattern = '{}*.txt'.format(a)
# or
#f'{a}*.txt'

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM