$ python --version
Python 3.9.0
$ pyenv --version
pyenv 1.2.27
Here are some txt files and csv files in a folder as follows.
files/
- txt1.txt
- csv1.csv
- txt2.txt
- csv2.csv
- txt3.txt
- csv3.csv
- txt4.txt
- csv4.csv
- txt5.txt
- csv5.csv
I want to reorganize the files in the folder by file type.
And the final result will be this.
reorganization/
- txt/
- txt1.txt
- txt2.txt
- txt3.txt
- txt4.txt
- txt5.txt
- csv/
- csv1.csv
- csv2.csv
- csv3.csv
- csv4.csv
- csv5.csv
import os
import shutil
try:
path = "./reorganization"
if not(os.path.isdir(path)):
os.mkdir(path)
list = os.listdir("./files")
for index, value in enumerate(list):
(name, ext) = os.path.splitext(value)
type_folder_path = f"{path}/{ext[1:]}"
if not(os.path.isdir(type_folder_path)):
os.mkdir(type_folder_path)
shutil.copyfile(f"./files/{value}", f"{type_folder_path}/{value}")
except OSError:
print (f"Failed" )
else:
print (f"Success")
use os.path.isdir()
function to check if the folder exists or not.
path = "./reorganization"
if not(os.path.isdir(path)):
os.mkdir(path)
use os.listdir()
function to get the file list in the folder.
list = os.listdir("./files")
for index, value in enumerate(list):
#...
use os.path.splitext()
funciton to get file's extension, and then use shutil.copyfile()
to copy the file to target path.
for index, value in enumerate(list):
(name, ext) = os.path.splitext(value)
type_folder_path = f"{path}/{ext[1:]}"
if not(os.path.isdir(type_folder_path)):
os.mkdir(type_folder_path)
shutil.copyfile(f"./files/{value}", f"{type_folder_path}/{value}")
os.path.isdir()
function to check if the folder exists or not.os.listdir()
function to get the file list in the folder.os.path.splitext()
funciton to get file's extension.shutil.copyfile()
to copy the file to target path.