How to write file paths to a txt file in Python

Viewed 464

I'm trying to multiple lines to a text file in Python

with open('output.txt', 'w') as outfile:
    outfile.write("open\n" +
                  "c:\files\file.scr"+
                  "close"
                 )

The file path isn't written correctly,

   open
    c:iles\drawing.dwgclose

Could someone suggest how to write the file path?

2 Answers

You can make the string raw by adding r in front:

with open('output.txt', 'w') as outfile:
    outfile.write("open\n" +
                  r"c:\files\file.scr"+
                  "close"
                 )

You will have to escape \ in strings

with open('output.txt', 'w') as outfile:
    outfile.write("open\n" +
                  "c:\\files\\file.scr"+
                  "close"
                 )
Related