TLanni
TLanni

Reputation: 340

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?

Upvotes: 0

Views: 120

Answers (2)

Krishnakanth Allika
Krishnakanth Allika

Reputation: 790

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'

Upvotes: 2

Ajay Kumar Chawla
Ajay Kumar Chawla

Reputation: 67

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('/','_');

Upvotes: 0

Related Questions