代码清理和有关使用导入操作系统的问题

时间:2019-05-28 00:31:43

标签: python-3.x mkdir shutil

我想这更像是对我的代码的批评,但是我想看看是否有一种更干净的替代方法可以写出我所做的事情。另外,作为Python的最佳实践,我是否不应该导入os和sys?有什么好的选择?

作为背景,我开始了一个新角色,希望跟上我的python,但要自动处理一些无聊的事情。我想让客户的便笺和文件尽可能地井井有条,所以我要做的是创建一个脚本,该脚本将使用我的自定义输入来创建新目录,然后将Notes文本文件的格式复制到新目录中。该脚本工作正常,但我觉得它有点草率。

#! python3
# Python script to create directory, and copy text file for notes

import sys
import os
from shutil import copyfile

# define the path to the location and use name for the title of your 
directory
path = "/Users/myname/"
name = path + sys.argv[1]

#create the directory with access rights if you want them to be there
try:
  os.mkdir(name)
except OSError:
  print("Creation of directory %s failed" % name)
else:
  print("Successfully created the directory %s" % name)

copyfile('/Users/myname/Notes', name + '/Notes')

当我调用脚本时,在脚本名称之后输入的内容就是我打算用来调用新目录的内容。 (下面,“ NewName”是我希望调用新目录的名称。)

例如python3 create.py NewName

然后,如果创建成功,那么我的主目录中的Notes文件将被复制到新创建的目录中。

0 个答案:

没有答案