python - 操作系统模块脚本做的事情但是在终端上抛出错误
问题描述
我只是使用python编写一个.py脚本来创建目录和使用os模块在里面创建一个文件这只是一个简单的脚本,如果不存在则创建目录,如果存在则删除它,因为我开发了这个脚本看看这个
import os
def new_directory(directory, filename):
# Before creating a new directory, check to see if it already exists
if os.path.isdir(directory) == False:
os.mkdir(directory)
else:
path=os.path.join(directory,filename)
os.remove(path)
os.rmdir(directory)
# Create the new file inside of the new directory
os.chdir(directory)
with open (filename,'w') as file:
pass
# Return the list of files in the new directory
return os.listdir(directory)
print(new_directory("PythonPrograms", "script.py"))
简单的脚本但是它完成了证明目录和创建文件的工作 但是当我查看终端时它会抛出错误,就像 终端中的终端 o/p 它会抛出错误但在文件资源管理器中它确实创建了文件我不明白为什么会发生这种情况希望你能带来有意义的答案
解决方案
如果目录已经存在(在 else 块中),您将删除该目录,但不会再次创建。os.chdir
因此失败。
您可以通过添加os.mkdir(directory)
到 else 块来解决此问题。
请注意,此设置有一个问题:如果目录不为空,os.rmdir 将无法工作,如果您向该目录写入了不同的文件,则可能会发生这种情况。即使您解决了这个问题,删除目录也可能是个好主意。
当目录不存在时,该程序可以正常工作,这就是它有时工作的原因(每两次尝试精确一次)
更新:
import os
def new_directory(directory, filename):
# Before creating a new directory, check to see if it already exists
if os.path.isdir(directory):
path = os.path.join(directory, filename)
os.remove(path)
os.rmdir(directory) # Because of this, os.mkdir below is needed
os.mkdir(directory)
# Create the new file inside of the new directory
os.chdir(directory)
with open (filename,'w') as file:
pass
# Return the list of files in the new directory
return os.listdir(directory)
print(new_directory("PythonPrograms", "script.py"))
推荐阅读
- javascript - 如何使用 VueJS 添加实时搜索?
- android - LG 智能手机独有的 VerifyError
- python - Argparse - AttributeError:“命名空间”对象没有属性
- javascript - 为什么 setAttribute 'false' 可以在另一个按钮上工作,但不能在 Javascript 中的 self 上工作?
- r - R中使用igraph的网络图的高内存使用率
- powershell - 创建 PowerShell 脚本模板以轻松进行组管理
- javascript - 如何使用 JavaScript 或 JQuery 连接 iframe 源的链接和输入?
- html - 如何在 Web 的 React Js 组件中使用 api?
- python - 如何在“for循环”之后将我的结果(输出)放入二维列表或嵌套列表中?
- flutter - 无法从函数“fetchPromotions”返回类型为“Resut”的值,因为它的返回类型为 Future
- >