Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 创建包含'/';python中的文件名_Python 2.7_File Handling - Fatal编程技术网

Python 2.7 创建包含'/';python中的文件名

Python 2.7 创建包含'/';python中的文件名,python-2.7,file-handling,Python 2.7,File Handling,如果文件名包含“/”,如何在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] invali

如果文件名包含“/”,如何在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'
回溯(最近一次呼叫最后一次):
文件“9.py”,第2行,在
f=打开(url,'w')
IOError:[Errno 22]无效的模式('w')或文件名: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的文件

您不能创建名称中带有路径分隔符的文件名。你的操作系统不允许这样做。
/
是为文件路径(目录)的各个元素保留的。如果路径存在,您可以创建这样的文件(当然没有http前缀!),在这种情况下,您只需创建一个名为
index.html
的文件。