如何在Python中动态转义/输入文件名

时间:2019-03-19 13:34:39

标签: python python-2.7 file-io escaping

我有一个程序可以写入某些文件,文件名是即时生成的,并且可以随机包含特殊字符。

只要这些特殊字符中有/,代码就会将其视为Linux的操作系统路径分隔符。

我如何动态地逃脱它?

我遇到的问题的演示:

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

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

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。

1 个答案:

答案 0 :(得分:0)

正如@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