简体   繁体   中英

Writing a function to move two files with the same name (with different file extensions) to a folder with the same name in python

I have folders set up in the following format:

AAPL_176546 (empty subfolder) AAPL_2000 (empty subfolder) AAPL_30234 (empty subfolder) AAPL_176546.mp3 AAPL_176546.txt AAPL_2000.mp3 AAAPL_2000.txt AAPL_30234.mp3 AAPL_30234.txt

I am looking to iterate through the folder and move both the corresponding.txt and.mp3 files into the subfolders (for instance move AAPL_176546.mp3 & AAPL_176546.txt into AAPL_176546).

I have tried:

import os import shutil

srcpath = "C:/Users/xeb15154/OneDrive - University of Strathclyde/Audio Files (5,506)/AAPL/" destpath = "C:/Users/xeb15154/OneDrive - University of Strathclyde/Audio Files (5,506)/AAPL/"

for root, subFolders, files in os.walk(srcpath): for file in files: subFolder = os.path.join(destpath, file) if not os.path.isdir(subFolder): os.makedirs(subFolder) shutil.move(os.path.join(root, file), subFolder)

but this creates folders for each file ie subfolders named AAPL_176546.mp3 & AAPL_176546.txt with the corresponding files stored within. Furthermore, when using the above code with directories that have files with differing filename lengths it again fails.

Any help on the matter would be greatly appreciated!

I am looking to iterate through the folder and move both the corresponding.txt and.mp3 files into the subfolders (for instance move AAPL_176546.mp3 & AAPL_176546.txt into AAPL_176546).

I suggest usingos.path.splitext function, it does split filename into proper name and extenstion (including last dot)

import os
name1, ext1 = os.path.splitext("AAPL_176546.mp3")
print(name1)
name2, ext2 = os.path.splitext("AAPL_176546.txt")
print(name2)

output

AAPL_176546
AAPL_176546

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