【问题标题】:create file containing '/' in file name in python在python中创建文件名中包含'/'的文件
【发布时间】:2016-10-15 11:53:52
【问题描述】:

如果文件名包含'/',如何在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'

【问题讨论】:

  • 您无法创建名称中带有路径分隔符的文件名。你的操作系统不允许。 / 保留用于分隔文件路径(目录)的元素。
  • 你可以创建一个像这样的文件如果路径存在(肯定没有http前缀!)在这种情况下你只需创建一个名为index.html的文件。

标签: python-2.7 file-handling


【解决方案1】:

使用 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 的文件

【讨论】:

    猜你喜欢
    • 2016-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-14
    • 2016-02-23
    • 2020-05-02
    • 2018-02-22
    • 1970-01-01
    相关资源
    最近更新 更多