Reputation: 15
I have folder with 1500 txt files and also folder with 20000 jpg files. 1500 of jpg files are named the same as txt files. I need that these jpg files with names similar to txt files to be moved to another folder.
To put it simply, I have txt files from 1(1) to 5(500), I need to move only files with the name from 1(1) to 5(500) from the folder with jpg files from 0(1) to 9(500).
I tried to write a program in Python via shutil, but I don't understand how to enter all 1500 valuse, so that only these files are moved.
Please tell me how to do this? Thanks in advance!
I found all the names of txt files and tried to copy pictures from another folder with the same names.
Example on pictures:
I have this names
I need to copy only this images, because their names are the same as the names of txt:
import os
import glob
import shutil
source_txt = 'C:\obj\TXT'
dir = 'C:\obj\Fixed_cars'
vendors =['C:\obj\car']
files_txt = [os.path.splitext(filename)[0] for filename in os.listdir(source_txt)]
for file in vendors:
for f in (glob.glob(file)):
if files_txt in f: # if apple in name, move to new apple dir
shutil.move(f, dir)
Upvotes: 0
Views: 598
Reputation: 131
Well, using this answer on looping through files of a folder you can loop through the files of your folder.
import os
directory = ('your_path_in_string')
txt_files = []
for filename in os.listdir(directory):
if filename.endswith(".txt"):
txt_files.append(filename.rstrip('.txt'))
for filename in os.listdir(directory):
if (filename.endswith(".jpg") and (filename.rstrip('.jpg') in txt_files)):
os.rename(f"path/to/current/{filename}", f"path/to/new/destination/for/{filename}")
for the the moving file part you can read this answer
Upvotes: 0