在 python 中创建文件名中包含“/”的文件
create file containing '/' in file name in python
如果文件名包含“/”,我如何在 python 中创建文件
url='https://www.udacity.com/cs101x/index.html'
f=open(url,'w')
f.write('123')
f.close()
以上代码会产生错误,如
Traceback (most recent call last):
File "9.py", line 2, in <module>
f=open(url,'w')
IOError: [Errno 22] invalid mode ('w') or filename:https://www.udacity.com/cs101x/index.html'
使用 os.path.basename() 来隔离文件名。
import os
url='https://www.udacity.com/cs101x/index.html'
filename = os.path.basename(url)
f=open(filename,'w')
f.write('123')
f.close()
这将创建一个名为 index.html
的文件
如果文件名包含“/”,我如何在 python 中创建文件
url='https://www.udacity.com/cs101x/index.html'
f=open(url,'w')
f.write('123')
f.close()
以上代码会产生错误,如
Traceback (most recent call last):
File "9.py", line 2, in <module>
f=open(url,'w')
IOError: [Errno 22] invalid mode ('w') or filename:https://www.udacity.com/cs101x/index.html'
使用 os.path.basename() 来隔离文件名。
import os
url='https://www.udacity.com/cs101x/index.html'
filename = os.path.basename(url)
f=open(filename,'w')
f.write('123')
f.close()
这将创建一个名为 index.html
的文件