简体   繁体   中英

Saving file with a name containing / at the destination folder in python

I am saving emails from outlook to the local folder.Folder path is following.

folder_path=r"C:\Documents\emails

filename is the subject of the email message as the following

subject=email_message.subject

so the final_path will be

final_path=os.path.join(folder_path,subject+".eml")

sometimes the subject contains "/" and then it gives the following error

[Error2] No such file or directory: 'C:\\Documents\\emails\\test1/email_123'

I think this is because that extra "/" in the subject line (subject was "test1/email_123")

How can I fix this?

This depends on how you want to treat the / in the subject line. Use the .replace() function on the subject accordingly.

Ignore /

subject=email_message.subject.replace("/", "")

Then the directory would be: 'C:\Documents\emails\test1email_123'

Treat / as a directory structure

subject=email_message.subject.replace("/", "\")

Then the directory would be: 'C:\Documents\emails\test1\email_123'

Treat / as a special character

If a / means something else in your organization like a hyphen or an underscore then use it.

subject=email_message.subject.replace("/", "-")

Then the directory would be: 'C:\Documents\emails\test1-email_123'

you should replace the letter with something else.

like 'C:\Documents\emails\test1/email_123' should be converted into 'C:\Documents\emails\test1_email_123'

this can be done by putting one line before final_path=os.path.join(folder_path,subject+".eml")

subject.replace('/','_');

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