简体   繁体   中英

Python regex match in paramiko sftp local filepath

I'm trying to send a file using python's paramiko module over SFTP. The problem is my script won't know the whole file path. For example, here is the local path I'm trying to get the file from:

\\buildserver\builds\1.2.34.45.78910_01JAN17\filename.txt

The problem is that I only have the first part of the third folder ( 1.2.34.45.78910_ ) and not the date that follows it ( 01JAN17 ). To get around this I have been trying to use a regular expression to match just the first part of the folder name. Paramiko's put function in the sftp_client.py file takes the filepath as input, so is there any way to pass regex as input to this function?

Example input:

buildNumber = "1.2.34.45.78910"
localFilePath = "\\\\buildserver\\builds\\" + "re.match(r\"^{0}\")".format(buildNumber) + "\\filename.txt"
sftp.put(localFilePath, remoteFilePath)

Example output:

WindowsError: [Error 3] The system cannot find the path specified: '\\\\buildserver\\builds\\re.match(r"^1.2.34.45.78910")\\filename.txt'

I have tried using both the re and fnmatch modules but they don't seem to have the functionality I need since they both take the string to match as input in addition to the regex.

If regex matching in the middle of a filepath is impossible, any suggestions on how I can achieve this using a different method would be appreciated.

As mentioned in the comments by depperm, this can be solved not by using regex but instead by using os.path.isdir to search for directories that begin with the starting path and contain the build number I'm searching for.

Here is a code snippet (this is assuming you are only looking for one match, for multiple matches see stackoverflow.com/a/15313024/3462319):

path1 = "\\\\buildserver\\builds"

for i in os.listdir(path1):
    if os.path.isdir(os.path.join(path1,i)) and numberReplaced in i:
        path2 = i

path1 += "\\" + path2 + "\\filename.txt"
sftp.put(path1, remoteFilePath)

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