简体   繁体   中英

How do i make multiple folders with multiple subfolders from two lists in python

I am trying to create multiple folders (in current directory) from a list in a text file, then create multiple subfolders inside of each of these folders using another list.(I hope that is clear enough?) The text file is a list of approximately 40 dates.

Here is my code so far:

import os, sys



subfolder_names = ['1st Eng', '2nd eng', '3rd Eng', 'Chief Eng', 'Cryo Eng', 'Electrical Eng', 'Master', '1st Mate', '2nd Mate', '3rd Mate']
topfolder_names = []

with open('datelist.txt', 'r') as f:
    for line in f:
        line = line.strip('\n')
        topfolder_names.append(line)

This is where i get lost, (As i dont really know what i am doing) how do i get the 'topfolder_names' folders to have the 'subfolder_names' as sub folders?

for topfolder_name in topfolder_names:
    os.makedirs(os.path.join(topfolder_names, subfolder_names))

This is the error i get.

Traceback (most recent call last):
  File "C:\Users\Kids\Documents\Visual Studio 2015\Projects\Stormpetrel 
Refit\folder3.py", line 18, in <module>
    os.makedirs(os.path.join(topfolder_names, topfolder_names))
  File "C:\Python27\lib\ntpath.py", line 65, in join
    result_drive, result_path = splitdrive(path)
  File "C:\Python27\lib\ntpath.py", line 116, in splitdrive
    normp = p.replace(altsep, sep)
AttributeError: 'list' object has no attribute 'replace'

Thanks

UPDATE: I found a solution that seems to work, i used a nested loop.

for topfolder_name in topfolder_names:
    for subfolder_name in subfolder_names:
        os.makedirs(os.path.join(topfolder_name, subfolder_name))

The os.makedirs and os.join functions can each only work on a single folder name at a time. You're passing your whole list of subfolders all at once, which doesn't work.

Instead, try adding a second loop over the subfolders:

for top in topfolder_names:
    for sub in subfolder_names:
        os.makedirs(os.path.join(top, sub))

You could also combine the two loops into one using itertools.product . The loop would become:

for top, sub in itertools.product(topfolder_names, subfolder_names):

The product function returns an iterator, which yields two-tuples. The for loop is unpacking the two values from each tuple into top and sub .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM