简体   繁体   中英

Python (3.5) - Constructing String to Save File - String Contains Escape Characters

I am using Python (3.5) to loop through some .msg files, extract data from them, which contains a url to download a file and a folder that the file should go into. I have successfully extracted the data from the .msg file but now when I try to piece together the absolute file path for the downloaded file, the format ends up weird, with backslashes and \\t\\r.

Here's a shortened view of the code:

for file in files:
    file_abs_path = script_dir + '/' + file
    print(file_abs_path)

    outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
    msg = outlook.OpenSharedItem(file_abs_path)

    pattern = re.compile(r'(?:^|(?<=\n))[^:<\n]*[:<]\s*([^>\n]*)', flags=re.DOTALL)
    results = pattern.findall(msg.Body)

    # results[0] -> eventID
    regexID = re.compile(r'^[^\/\s]*', flags=re.DOTALL)
    filtered = regexID.findall(results[0])
    eventID = filtered[0]
    # print(eventID)

    # results[1] -> title
    title = results[1].translate(str.maketrans('','',string.punctuation)).replace(' ', '_') #results[1]
    title = unicodedata.normalize('NFKD', title).encode('ascii', 'ignore')
    title = title.decode('UTF-8')
    #results[1]
    print(title)

    # results[2] -> account
    regexAcc = re.compile(r'^[^\(\s]*', flags=re.DOTALL)
    filtered = regexAcc.findall(results[2])
    account = filtered[0]
    account = unicodedata.normalize('NFKD', account).encode('ascii', 'ignore')
    account = account.decode('UTF-8')
    # print(account)

    # results[3] -> downloadURL
    downloadURL = results[3]
    # print(downloadURL)
    rel_path = account + '/' + eventID + '_' + title + '.mp4'
    rel_path = unicodedata.normalize('NFKD', rel_path).encode('ascii', 'ignore')
    rel_path = rel_path.decode('UTF-8')
    filename_abs_path = os.path.join(script_dir, rel_path)
    # Download .mp4 from a url and save it locally under `file_name`:
    with urllib.request.urlopen(downloadURL) as response, open(filename_abs_path, 'wb') as out_file:
        shutil.copyfileobj(response, out_file)

    # print item [ID - Title] when done
    print('[Complete] ' + eventID + ' - ' + title)

    del outlook, msg

So as you can see I have some regex that extracts 4 pieces of data from the .msg. Then I have to go through each one and do some further fine tuning, but then have what I need:

eventID
# 123456

title 
# Name_of_item_with_underscord_no_punctuation 

account
# nameofaccount

downloadURL
# http://download.com/basicurlandfile.mp4

So this is the data I get, and I've print() it off and it doesn't have any weird characters. But when I try to construct the path for the .mp4 (filename and directory):

downloadURL = results[3]
# print(downloadURL)
rel_path = account + '/' + eventID + '_' + title + '.mp4'
rel_path = unicodedata.normalize('NFKD', rel_path).encode('ascii', 'ignore')
rel_path = rel_path.decode('UTF-8')
filename_abs_path = os.path.join(script_dir, rel_path)
# Download .mp4 from a url and save it locally under `file_name`:
with urllib.request.urlopen(downloadURL) as response, open(filename_abs_path, 'wb') as out_file:
    shutil.copyfileobj(response, out_file)

After doing this, the output I get from running the code is:

Traceback (most recent call last): File "sfaScript.py", line 65, in <module> with urllib.request.urlopen(downloadURL) as response, open(filename_abs_path, 'wb') as out_file: OSError: [Errno 22] Invalid argument: 'C:/Users/Kenny/Desktop/sfa_kenny_batch_1\\\\accountnamehere/123456_Name_of_item_with_underscord_no_punctuation\\t\\r.mp4'

TL;DR - QUESTION

So the filename_abs_path somehow got changed to C:/Users/Kenny/Desktop/sfa_kenny_batch_1\\\\accountnamehere/123456_Name_of_item_with_underscord_no_punctuation\\t\\r.mp4

I need it to be

C:/Users/Kenny/Desktop/sfa_kenny_batch_1/accountnamehere/123456_Name_of_item_with_underscord_no_punctuation.mp4

Thanks for any help provided!

Looks like your regex captured a tabulation char ( \\t ) and a linefeed char ( \\r ) in title

A quickfix for this would be:

title  = title.strip()

(before composing the filename)

which removes all "blank" chars, including tabulations and carriage return chars.

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