0

I want to name a file containing special characters, but I get an error when I try to do so

with open('My filename: one | two.txt', 'a') as f:
    f.write('something') 

and get this error :

OSError: [Errno 22] Invalid argument: 'My filename: one | two.txt'

How can I name a file containing special characters?

mxidentic
  • 1
  • 2

1 Answers1

2

It depends on the OS, but for Microsoft, these are the specific characters not allowed in filenames and vertical bar (|) is one of them.

From https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file:

Use any character in the current code page for a name, including Unicode characters and characters in the extended character set (128–255), except for the following:

  • The following reserved characters:

    • < (less than)
    • > (greater than)
    • : (colon)
    • " (double quote)
    • / (forward slash)
    • \ (backslash)
    • | (vertical bar or pipe)
    • ? (question mark)
    • * (asterisk) Integer value zero, sometimes referred to as the ASCII NUL character.
  • Characters whose integer representations are in the range from 1 through 31, except for alternate data streams where these characters are allowed. For more information about file streams, see File Streams.

  • Any other character that the target file system does not allow.

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251