尝试创建文件时出现文件名错误

时间:2017-01-14 15:11:11

标签: python file jupyter-notebook

我正在尝试使用以下代码创建文件

testnum= '01'
file_name = 'output\test'+ testnum +'.txt'
with open(file_name,'w',encoding='utf-8') as file:
    file.write('Hallo')

但是我收到以下错误消息:

---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
<ipython-input-15-322cc04151aa> in <module>()
      1 testnum= '01'
      2 file_name = 'output\test'+ testnum +'.txt'
----> 3 with open(file_name,'w') as file:
      4     file.write('Hallo')

OSError: [Errno 22] Invalid argument: 'output\test01.txt'

我正在使用Jupyter笔记本。

1 个答案:

答案 0 :(得分:1)

\t是制表符。您需要通过加倍\来转义\,以获得实际的testnum= '01' file_name = 'output\\test'+ testnum +'.txt' # Here -------------^ 字面值:

effect: 'slide',