0

I am trying to move a specific number of certain files.

for file_names in file_names[:12]:
    if os.path.isfile(file_names):
        if file_names.endswith('.txt'):
            shutil.move(os.path.join(dir_path, file_names), nf)

The original directory could have 0 to 70 something files no sub folders. It is supposed to run through and create a new folder. Then move 12 txt files into that folder, then repeat. The issue comes from the fact. That the array number counts 12 items, including the folders and moves only the txt items in that array. Sorry hopefully using the right terminology.

So, what happens is it creates the first folder and moves 11 txt files. Then the next folder and moves 9 text files and so on.

So how do get it move 12 text files consistently even with new folders being added to the directory?

w j
  • 43
  • 1
  • 7
  • Create a counter variable initialized to zero. Iterate with the for-loop through all `file_names`. Check in each iteration if counter reached 12, if so: `break`. Increment counter each time a real file was moved. – Michael Butscher Apr 13 '23 at 14:17

2 Answers2

1

There are many ways you could get around this. Maybe use glob to search the directory recursively for files ending in '.txt'.

Using basic functions, how about filtering the list of files first?

file_names_filtered = [x for x in file_names if os.path.isfile(x) and x.endswith('.txt')]

for file_names in file_names_filtered[:12]:
        shutil.move(os.path.join(dir_path, file_names), nf)
jklebes
  • 136
  • 6
0

The issue is that you are subsetting paths in the folder (i.e. for file_names in file_names[:12]:) before you check if each of them are files and not directories (i.e. if os.path.isfile(file_names):). You may need to rethink the logic of your script.

There are many ways to do this. One way is use a counter and maintain a list of txt files in your source directory.

Something like this (code note tested):

# Set the source directory
source_dir = 'path/to/source/dir'

# Get a list of all the text files in the source directory
txt_files = [f for f in os.listdir(source_dir) if f.endswith('.txt')]

# Set a counter for the new folder names
new_folder_count = 1

# Iterate through the list of text files, moving 12 at a time until none are left
while len(txt_files) > 0:
    # Create the destination directory for the current batch of files
    dest_dir = os.path.join(source_dir, f'nf_{new_folder_count}')
    os.mkdir(dest_dir)

    # Move the first 12 text files to the destination directory
    for file_name in txt_files[:12]:
        file_path = os.path.join(source_dir, file_name)
        shutil.move(file_path, dest_dir)

    # Remove the moved files from the list of text files
    txt_files = txt_files[12:]

    # Increment the new folder counter
    new_folder_count += 1
dogekali
  • 91
  • 6