mkdir 子文件夹在终端中工作但不是来自 python

mkdir with subfolders working in terminal but not from python

我想创建一些带有子文件夹的文件夹,并使用这个 python3 脚本来读取 csv 文件并为我创建目录。

from subprocess import call
import csv

def csv_dict_reader(file_obj):
    """
    Read a CSV file using csv.DictReader
    """
    reader = csv.DictReader(file_obj, delimiter=',')
    for line in reader:
        sanitized_name = line["course"].replace(" ", "-").lower()

        command = 'mkdir -p ' + sanitized_name + '/week_{1..'+ line["week"] +'}/{slides,exercise,assignment}'
        call(command)


if __name__ == "__main__":
    with open("courses.csv") as f_obj:
        csv_dict_reader(f_obj)

我原以为它会执行这种命令

mkdir -p algorithmic-toolbox/week_{1..6}/{slides,exercise,assignment}

它在终端上运行良好,并创建了一个名为 algorithmic-toolbox 的文件夹,其中包含 week1 to week6 中的 6 个文件夹,然后每个文件夹包含 slides, exercises and assignment 个文件夹。

示例 csv 如下所示:

course,week
Algorithmic Toolbox,6
Data Structures,4
Algorithms on Graphs,5

我在 运行 python 脚本时遇到此错误。

Traceback (most recent call last):
  File "course-folder.py", line 18, in <module>
    csv_dict_reader(f_obj)
  File "course-folder.py", line 13, in csv_dict_reader
    call(command)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 267, in call
with Popen(*popenargs, **kwargs) as p:
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 709, in __init__
restore_signals, start_new_session)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 1344, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'mkdir -p algorithmic-toolbox/week_{1..6}/{slides,exercise,assignment}': 'mkdir -p algorithmic-toolbox/week_{1..6}/{slides,exercise,assignment}'

不知道为什么当我用 -p 创建目录时它说 FilenotFoundError 如果父目录不存在,它应该创建父目录。

mkdir -p algorithmic-toolbox/week_{1..6}/{slides,exercise,assignment}

我相信如果不将 shell=True 参数传递给 subprocess.call,上述命令中使用的参数扩展将无法工作。这样 Python 将在中间 shell 进程中执行命令。

如果您希望您的脚本独立于平台,您可以改用 os.mkdir 并处理 Python 中的逻辑。