0

I want to use '/' as a character in a filename when saving a file.

with open('first_part.whatever', 'w') as f:
    f.write('file things')
    f.close()

This will save a file as expected, but

with open('first_part/second_part.whatever', 'w') as f:
    f.write('file things')
    f.close()

will not.

FileNotFoundError: [Errno 2] No such file or directory: 'first_part/second_part.whatever'

is the error message, which is clear enough. Yet, I don't know how to say "I want the entire string to be the filename; treat the slashes as just another character, not as a new directory". How do I do that?

chicks427
  • 41
  • 1
  • 4
  • 1
    You don't. A slash is not a valid character in a file or directory name on POSIX-compliant systems. You _could_ use a Unicode char that looks like a slash, but people will rightfully hate you for doing that. :) – PM 2Ring Dec 20 '16 at 11:10
  • The HFS+ file system is very liberal in what it permits in a file name component, but Unix doesn't allow the use of slash because it's the path separator char. So while you may be able to create such filenames they will generally not work correctly in any software that uses standard Unix file manipulation functions (and that includes the Python standard library). And of course, such file names will not be portable to Linux and most other Unix-like systems. – PM 2Ring Dec 20 '16 at 11:21
  • For more info, please see [What are invalid characters for a file name under OS X?](http://superuser.com/questions/326103/what-are-invalid-characters-for-a-file-name-under-os-x) and the questions it links to. – PM 2Ring Dec 20 '16 at 11:25

0 Answers0