首页 > 解决方案 > 操作系统模块脚本做的事情但是在终端上抛出错误

问题描述

我只是使用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 它会抛出错误但在文件资源管理器中它确实创建了文件我不明白为什么会发生这种情况希望你能带来有意义的答案

标签: pythonpython-3.xoperating-system

解决方案


如果目录已经存在(在 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"))

推荐阅读