0

So I have a script that needs to print to a file in a different directory. I give that absolute path and python doesn't like it.

Here's where the file is located: C:\Users\Owner\Documents\Senior_design\QT_Library\build-TransmitterPlot-Desktop_Qt_5_0_2_MSVC2010_32bit-Debug\numbers.txt

(I know, long path, but QT plotter makes the file names really long)

I typed:

textfile = open('C:\Users\Owner\Documents\Senior_design\QT_Library\build-TransmitterPlot-Desktop_Qt_5_0_2_MSVC2010_32bit-Debug\numbers.txt', 'w')

And I get this error:

IOError: [Errno 22] invalid mode ('w') or filename:

I've read that I can use relative paths, but I am unsure how to give it a relative path with so many directories to go through.

Thanks!

Aya
  • 39,884
  • 6
  • 55
  • 55
Lee
  • 1
  • 1

2 Answers2

3

The problem is that python is interpreting the backslashes in your path as escape sequences:

>>> 'C:\Users\Owner\Documents\Senior_design\QT_Library\build-TransmitterPlot-Desktop_Qt_5_0_2_MSVC2010_32bit-Debug\numbers.txt'
'C:\\Users\\Owner\\Documents\\Senior_design\\QT_Library\x08uild-TransmitterPlot-Desktop_Qt_5_0_2_MSVC2010_32bit-Debug\numbers.txt'

Notice that both \b and \n get translated to something else. Use a "raw" string instead:

>>> r'C:\Users\Owner\Documents\Senior_design\QT_Library\build-TransmitterPlot-Desktop_Qt_5_0_2_MSVC2010_32bit-Debug\numbers.txt'
'C:\\Users\\Owner\\Documents\\Senior_design\\QT_Library\\build-TransmitterPlot-Desktop_Qt_5_0_2_MSVC2010_32bit-Debug\\numbers.txt'
mgilson
  • 300,191
  • 65
  • 633
  • 696
1

I believe this answer here may be of help.

Essentially, your backslashes are causing issues.

Community
  • 1
  • 1
basica
  • 67
  • 1
  • 2
  • 11