我想创建一些带有子文件夹的文件夹,并且有这个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}'
当我使用FilenotFoundError
创建目录时,不确定为什么会显示-p
,如果它们不存在则应该创建父目录。
答案 0 :(得分:1)
mkdir -p algorithmic-toolbox/week_{1..6}/{slides,exercise,assignment}
我认为如果不将shell=True
参数传递给subprocess.call
,上述命令中使用的参数扩展将无法工作。这样Python就会在中间shell进程中执行命令。
如果您希望脚本与平台无关,则可以使用os.mkdir
并在Python中处理逻辑。