如何在 python 中动态转义 / in 文件名

How to escape / in filename dynamically in python

我有一个写入特定文件的程序,文件名是动态生成的,可以随机包含特殊字符。

只要这些特殊字符中有 /,代码就会将其视为 linux.

的 OS 路径分隔符

我怎样才能动态地逃避这个?

展示我是什么 运行 进入:

import random
special_chars = "$^&%*^(&/"
selected = random.choice(special_chars)
#selected = "/"
with open(__file__ + "%s.txt" % selected) as f:
    f.write("Hello")

当它是 / 以外的任何其他字符时运行得很好,但是当您将 selected 设置为 / 时: 错误:

Traceback (most recent call last):
  File "./a.py", line 7, in <module>
    with open(__file__ + "%s.txt" % selected, 'w') as f:
IOError: [Errno 20] Not a directory: './a.py/.txt'

python 2.7 只请。

正如@Nullman 所说,/ 不是 Linux 中文件名的有效字符:

$ touch a

$ touch a/b/c.txt
touch: cannot touch 'a/b/c.txt': Not a directory

切勿在文件名中使用 /\ 符号,因为它会产生许多意想不到的结果。例如:

Linux终端机:

$ touch a\b\c
$ ls
abc

IPython 3:

In [1]: with open('a\b\c', 'w') as f:
   ...:     f.write(' ')
   ...:     

In [2]: ls
a?\c