1

I am writing a Python script to create directories for a given term and course. I would like to make use of the Python modules os, sys, and getopt (with both short and long form options) so that the running script would look like:

>python directory.py –t fall2013 –c cs311-400 
>python directory.py –-term fall2013 –-class cs311-400

The code that I have write now looks like this:

import os
import sys
import getopt

term = ""
course = ""

options, args = getopt.getopt(sys.argv[1:], 't:c:', ['term=', 'course='])

for opt, arg in options:
    if opt in ('-t', '--term'):
        term = arg
    elif opt in ('-c', '--course'):
         course = arg

After this, I have a function that takes in the term and course an uses os.mkdir and such:

def make_folders(term, course):
    if not os.path.isdir(term + course):
        os.mkdir(term + course)
        path = os.path.join(term + course, "assignments")
        os.makedirs(path)

        path = os.path.join(term + course, "examples")
        os.makedirs(path)

        path = os.path.join(term + course, "exams")
        os.makedirs(path)

        path = os.path.join(term + course, "lecture_notes")
        os.makedirs(path)

        path = os.path.join(term + course, "submissions")
        os.makedirs(path)

make_folders(term, course)

For some reason, the folder that gets made only has a name that represents the term rather than both the term and the course. I feel like this might have something to do with my use of getopt, but I'm not certain. Any advice?

4

3 回答 3

1

os.path.join是一个聪明的功能。只需传递所需数量的文件夹:

>>> import os
>>> os.path.join("first", "second", "third")
'first/second/third'
于 2014-01-21T07:42:02.160 回答
1

当您编写 时,Python甚至在看到它们之前就直接将term + course字符串连接起来。也就是说,如果,说,和,那么两者之间没有任何东西。termcourseos.path.join()term == "fall2013"course == "cs311-400"term + course == "fall2013cs311-400"

一种解决方法是在术语和课程之间插入一个明确的斜线,如term + "/" + course. 但是,由于您可能已被指示使用os.path.join()(无论如何这是一个好主意),您可以将要加入的所有路径组件作为单独的参数传递给它,并让它为您处理加入它们:

path = os.path.join(term, course, "exams")

此外,还有一些关于您的作业以及一般良好 Python 编码的提示:

  • 虽然该getopt模块实际上并没有像评论中的 rtrwalker 声称的那样被弃用,但除非出于某种原因(例如,作业告诉您),argparse否则您可能最好使用它。getopt

  • 您的代码看起来非常重复。重复代码是一种“气味”,应该表明需要循环,可能像这样:

    dirs = ("assignments", "examples", "exams", "lecture_notes", "submissions")
    for folder in dirs:
        path = os.path.join(term, course, folder)
        os.makedirs(path)
    
于 2014-01-21T07:51:41.483 回答
0

I'm actually in your class; at least I'm almost positive I am. Was running into this exact problem and was having trouble getting that sub-directory. A google search landed me here! Well, after a few more googles and LOTS of troubleshooting, found the answer to our problem!

os.makedirs(''+term+'/'+course+'')      
path = os.path.join(''+term+'/'+course+'', "exams")
os.makedirs(path)

That should clean it up for you and give your your new directory and sub-directories! Good luck with the rest of the assignment.

于 2013-10-14T09:04:36.353 回答