separate files in folder according to extension python - python

I have a folder that contains a group of files with different extension like .txt , .png , .pdf etc.
I want to organize the files and save them in different folders, for example, each file.txt in one folder and file.png in an another folder and file.pdf in an another folder etc.
import os
path = r'C:\Users\ibrahim\Desktop\test'
text_files = [f for f in os.listdir(path) if f.endswith('.txt')]
text_files
In this script how can I separately move files into different folders?

Something like this should work:
import os
import shutil
# Note we have to escape our backslashes here
path = "C:\\Users\\ibrahim\\Desktop\\test\\"
for f in os.listdir(path):
# Path to the original file
original_file_path = os.path.join(path, f)
# Only operate on files
if os.path.isfile(original_file_path):
# Get file name portion only
file_name = os.path.basename(original_file_path)
# Get the extension of the file and create a path for it
extension = f.split(".")[-1]
extension_path = os.path.join(path, extension)
# Create the path for files with the extension if it doesn't exist
if not os.path.exists(extension_path):
os.makedirs(extension_path)
# Copy the files into the new directory (copying is safer than moving, just so we can ensure it works as expected)
shutil.copyfile(original_file_path, os.path.join(extension_path, file_name))
Note that this will not be clever in anyway, .jpeg files will go into a different folder than .jpg files.

Try this,
import os
import shutil
txt_path = os.path.join(os.getcwd(), "text")
png_path = os.path.join(os.getcwd(), "png")
pdf_path = os.path.join(os.getcwd(), "pdf")
if not os.path.isdir(txt_path):
os.makedirs(txt_path)
print("text folder created")
if not os.path.isdir(png_path):
os.makedirs(png_path)
print("png folder created")
if not os.path.isdir(pdf_path):
os.makedirs(pdf_path)
print("pdf folder created")
#files = ['a.png' , 'b.pdf', 'c.txt']
files = [f for f in os.listdir(path)]
for file in files:
file_path = os.path.join(os.getcwd(), file)
if file_path.endswith('.txt')==True:
print('move file to text folder')
shutil.move(file_path, txt_path)
if file_path.endswith('.png')==True:
print('move file to png folder')
shutil.move(file_path, png_path)
if file_path.endswith('.pdf')==True:
print('move file to pdf folder')
shutil.move(file_path, pdf_path)

Related

Save outputs to new directory in Python

I am trying to identify all .kml in a specific directory and save them into a new directory. Is this possible? I'm able to print the file path but I would like to use Python to copy those files to a new directory.
Here is my code so far:
import os
# traverse whole directory
for root, dirs, files in os.walk(r'C:\Users\file_path_here'):
# select file name
for file in files:
# check the extension of files
if file.endswith('.kml'):
# print whole path of files
print(os.path.join(root, file))
Try this:
import os
# traverse whole directory
for root, dirs, files in os.walk(r'C:\Users\file_path_here'):
# select file name
for each_file in files:
# check the extension of files
if each_file.endswith('.kml'):
# print whole path of files
print(os.path.join(root, file))
kml_file = open(each_file, "r")
content = kml_file.read()
file.close()
with open('newfile.kml', 'w') as f:
f.write(content)

How to swap files with one file extension with identically named but different files with a different extension and maintain the directory structure?

I work in audio and I need a number of files transcribed by a third party. To do so I have to swap out an entire directory of .wav files with .mp3s I have compressed while still maintaining the file directory. It's about 20,000 files.
e.g.
wav:
Folder1
Folder 1a
sound1.wav
sound2.wav
Folder 1b
sound3.wav
sound4.wav
Folder2
Folder 2a
Folder 2aa
sound5.wav
sound6.wav
Folder 2ab
sound7.wav
Folder2b
sound8.wav
etc.
mp3:
Folder1
sound1.mp3
sound2.mp3
sound3.mp3
sound4.mp3
sound5.mp3
sound6.mp3
sound7.mp3
sound8.mp3
etc.
I had to group them together to do the batch compression in Adobe Audition, but now I would like to be able to switch them out with the wav files that are perfectly identical save for file extension as doing this manually is not a reasonable option.
Any help would be greatly appreciated. I have a little experience with python so that language is preferable, but I'm open to any solutions.
You can use a combination of glob and shutil to do this. Try running this script from inside Folder1.
from glob import glob
from shutil import move
import os
wav_files = glob('**/*.wav', recursive=True)
for wf in wav_files:
file_path = os.path.splitext(wf)[0]
file_head = os.path.split(file_path)[-1]
try:
move('./{}.mp3'.format(file_head),
'{}.mp3'.format(file_path))
except:
print('Could not find or move file {}.mp3, it may not exist.'.format(file_head))
What I understand is that you want the same directory structure for mp3 as for vaw.
You can:
browse the directory structure of vaw file and construct a mapping between base names (file names without extension) and relative path.
browse the directory structure, searching the mp3 files and find each relative path in the mapping, creating the target directory structure if missing and move the file in.
For instance:
import os
vaw_dir = 'path/to/MyVaw' # parent of Folder1...
musics = {}
for root, dirnames, filenames in os.walk(vaw_dir):
for filename in filenames:
basename, ext = os.path.splitext(filename)
if ext.lower() == '.wav':
relpath = os.path.relpath(root, vaw_dir)
print('indexing "{0}" to "{1}"...'.format(filename, relpath))
musics[basename] = relpath
else:
print('skiping "{0}"...'.format(filename))
mp3_dir = 'path/to/MyMp3'
out_dir = vaw_dir # or somewhere else
for root, dirnames, filenames in os.walk(vaw_dir):
for filename in filenames:
basename, ext = os.path.splitext(filename)
if ext.lower() == '.mp3' and basename in musics:
relpath = musics[basename]
path = os.path.join(out_dir, relpath)
if not os.path.exists(path):
print('creating directory "{0}"...'.format(path))
os.makedirs(path)
src_path = os.path.join(root, filename)
dst_path = os.path.join(path, filename)
if src_path != dst_path:
print('moving "{0}" to "{1}"...'.format(filename, relpath))
os.rename(src_path, dst_path)
else:
print('skiping "{0}"...'.format(filename))
print("Done.")

How can I scrape file names and create directories for each filename in Python?

I'm trying to scrape filenames inside a folder and then make directories for each filename inside another folder. This is what I've got so far but when I run it, it doesn't create the new folders in the destination folder. When I run it in the terminal it doesn't return any errors.
import os
import shutil
folder = "/home/ro/Downloads/uglybettyfanfiction.net/"
destination = "/home/ro/A Python Scripts/dest_test/"
# get each files path name
def ensure_dir(f):
d = os.path.dirname(f)
if not os.path.exists(d):
os.makedirs(d)
for files in os.listdir(folder):
new_path = folder + files
ensure_dir(new_path)
You've got a few mistakes. No need to use dirname and you should write to your destination, not the same folder:
def ensure_dir(f):
if not os.path.exists(f):
os.mkdir(f)
for files in os.listdir(folder):
new_path = destination + files
ensure_dir(new_path)

Move files from multiple directories to single directory

I am trying to use the os.walk() module to go through a number of directories and move the contents of each directory into a single "folder" (dir).
In this particular example I have hundreds of .txt files that need to be moved. I tried using shutil.move() and os.rename(), but it did not work.
import os
import shutil
current_wkd = os.getcwd()
print(current_wkd)
# make sure that these directories exist
dir_src = current_wkd
dir_dst = '.../Merged/out'
for root, dir, files in os.walk(top=current_wkd):
for file in files:
if file.endswith(".txt"): #match files that match this extension
print(file)
#need to move files (1.txt, 2.txt, etc) to 'dir_dst'
#tried: shutil.move(file, dir_dst) = error
If there is a way to move all the contents of the directories, I would be interested in how to do that as well.
Your help is much appreciated! Thanks.
Here is the file directory and contents
current_wk == ".../Merged
In current_wkthere is:
Dir1
Dir2
Dir3..
combine.py # python script file to be executed
In each directory there are hundreds of .txtfiles.
Simple path math is required to find source files and destination files precisely.
import os
import shutil
src_dir = os.getcwd()
dst_dir = src_dir + " COMBINED"
for root, _, files in os.walk(current_cwd):
for f in files:
if f.endswith(".txt"):
full_src_path = os.path.join(src_dir, root, f)
full_dst_path = os.path.join(dst_dir, f)
os.rename(full_src_path, full_dst_path)
You have to prepare the complete path of source file, and make sure dir_dst exists.
for root, dir, files in os.walk(top=current_wkd):
for file in files:
if file.endswith(".txt"): #match files that match this extension
shutil.move(os.path.join(root, file), dir_dst)

copying files from one folder to another

I'm trying to make a script that copies all the files other than the zipped files from a source folder to another destination folder and extract zipped files from the source folder to the destination, this is what i have come till this far:
import os
import zipfile
import shutil
myPath = "Source dir"
for root, dirs, files in os.walk(myPath):
for file in files:
if file.endswith('.zip'):
fh = open(file, 'rb')
z = zipfile.ZipFile(fh)
for name in z.namelist():
outpath = "destination dir"#Put the name of the destination folder
z.extract(name, outpath)
fh.close()
else:
fileList = os.listdir('source dir')
for f in fileList:
shutil.copy2(f, 'destination directory')
The code shows no error but there is no output too.
From Python Standard Library To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name) so you should write
fh = open(so.path.join(root,file))
to have the correct path.

Categories

Resources