Copy files of one extension

EasyOS Module Programs · 18 of 49

Write a Python program to copy only the files with a specific extension.

Advertisement
Output
['a.csv', 'c.csv']

Approach

  1. Filter names with endswith, then copy.

Solution

Python
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.

More os module programs

← All 49 OS Module Programs

Leave a Comment