Python Practice › OS Module Programs › Program 18
Copy files of one extension
Write a Python program to copy only the files with a specific extension.
Output
['a.csv', 'c.csv']
Approach
- Filter names with
endswith, then copy.
Solution
import osimport shutil os.makedirs("src", exist_ok=True)os.makedirs("only_csv", exist_ok=True)for name in ["a.csv", "b.txt", "c.csv"]: open(os.path.join("src", name), "w").close()for name in os.listdir("src"): if name.endswith(".csv"): shutil.copy(os.path.join("src", name), "only_csv")print(sorted(os.listdir("only_csv")))Output
['a.csv', 'c.csv']
Learn the concept
New to this topic? Read the lesson, then come back.