Natasha
Natasha

Reputation: 1521

How to write file paths to a txt file in Python

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?

Upvotes: 3

Views: 765

Answers (2)

David Erickson
David Erickson

Reputation: 16683

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"
                 )

Upvotes: 1

Shinva
Shinva

Reputation: 2304

You will have to escape \ in strings

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

Upvotes: 0

Related Questions