21

I'm not sure why, but for some reason, whenever I have "region" in the file name of the output file, it gives me this error:

IOError: [Errno 22] invalid mode ('w') or filename: 'path\regionlog.txt'

It does this for "region.txt", "logregion.txt", etc.

class writeTo:
    def __init__(self, stdout, name):
       self.stdout = stdout
       self.log = file(name, 'w') #here is where it says the error occurs

output = os.path.abspath('path\regionlog.txt')
writer = writeTo(sys.stdout, output) #and here too

Why is this? I really would like to name my file "regionlog.txt" but it keeps coming up with that error. Is there a way around it?

twlkyao
  • 14,302
  • 7
  • 27
  • 44
FaerieDrgn
  • 305
  • 2
  • 3
  • 9

4 Answers4

32

Use forward slashes:

'path/regionlog.txt'

Or raw strings:

r'path\regionlog.txt'

Or at least escape your backslashes:

'path\\regionlog.txt'

\r is a carriage return.


Another option: use os.path.join and you won't have to worry about slashes at all:

output = os.path.abspath(os.path.join('path', 'regionlog.txt'))
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
Pavel Anossov
  • 60,842
  • 14
  • 151
  • 124
1

In C standard language, \t, \n, \r are escape characters. \t is a transverse to the next TAB position. \n is a newline and \r is a carriage return. You should use \\r or /r, and you will solve the problem!

Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
JackChen
  • 71
  • 1
  • 2
  • Next time, check to make sure what you typed came out correctly on screen, as your `\\r` showed up like `\r`, which would not be at all helpful. – Nathan Tuggy Mar 14 '17 at 12:04
1

Additionaly, Python also gives this message when trying to open a file > 50 MB from a SharePoint shared drive.

https://support.microsoft.com/en-us/help/2668751/you-cannot-download-more-than-50-mb-or-upload-large-files-when-the-upl

-1

Another simple solution is changing the "\r" instances in the filename path to "\R"

Roee Anuar
  • 3,071
  • 1
  • 19
  • 33