gpt4 book ai didi

python - 如何动态创建目录并将文件输出到Python中

转载 作者:行者123 更新时间:2023-12-01 06:15:41 39 4
gpt4 key购买 nike

我有一个 python 脚本,它尝试根据用户输入动态创建目录树。这就是我的代码到目前为止的样子。

if make_directories:
os.makedirs(outer_dir)
os.chdir(outer_dir)
for car in cars:
os.makedirs(car)
os.chdir(car)
#create a bunch of text files and do other stuff,
os.chdir('../')
os.chdir('../')

我想知道是否有更好的方法来做到这一点?我不知道这样不断更改目录是否是一个不好的约定。

注意:Cars是用户提供的汽车名称列表,outer_dir是用户提供的目录名称

最佳答案

我倾向于进行路径操作而不是更改目录;只是因为当前目录有点“隐含状态”,而路径可以是明确的根目录。

if make_directories:
for car in cars:
carpath = os.path.join(outer_dir, car)
os.makedirs(carpath)
for fn in textfiles:
filepath = os.path.join(carpath, fn)
#... use filepath ...

关于python - 如何动态创建目录并将文件输出到Python中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3453329/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com