Issue
I would like to copy and paste csv files based on conditions from folders inside another folder.
The main folder's name is “main”, and there are folders inside it, namely main_1, main_2, main_3,......, and main_45. There are also csv files inside each folder, namely, a1, b2, c3, d4, e5,........z30.
I just want to copy a1.csv, b2.csv, and c3.csv from the folders and paste them into another empty folder. It looks too complex to me, but I am sure it would be easy for experts. Thanks in advance
Solution
os.walk
iterates through directory and show all files in string.
So iterate through main
folder and if the file name ends with .csv
, then copy it with shutil.copyfile
function
import os, shutil
for p, d, f in os.walk("main"):
for fname in f:
if fname.endswith(".csv"):
shutil.copyfile(os.path.join(p, f), os.path.join("ANOTHER EMPTY FOLDER NAME", f))
docs:
https://docs.python.org/3/library/os.html
https://docs.python.org/3/library/shutil.html
Answered By - minolee
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.