Let’s work with files and directories. Copying specific files between directories is a few lines of Python code job.
The shutil and path modules in Python can be used to copy only specific files from one directory to another. For example, if you want to copy only .txt files between directories on your hard drive, you can use the following code:
Pathlib copy file
import shutil from pathlib import Path source_path = Path("c:/foobar/") text_files = source_path.glob("*.txt") destination = Path("c:/MyProject/MyFiles/MyDirectory2020/") for file in text_files: shutil.copy(str(file), str(destination))
Key Takeaways
- The shutil and path modules in Python can be used to copy only specific files from one directory to another.
- The `Pathlib` module provides a convenient way to work with files and directories in Python.
- The `glob()` method can be used to find all files that match a certain pattern.
- The `shutil.copy()` function can be used to copy a file from one location to another.
FAQ
- Q: What is the `source_path` variable?
- A: The `source_path` variable is a Path object that represents the source directory.
- Q: What is the `text_files` variable?
- A: The `text_files` variable is a list of Path objects that represent the .txt files in the source directory.
- Q: What is the `destination` variable?
- A: The `destination` variable is a Path object that represents the destination directory.
- Q: What does the `shutil.copy()` function do?
- A: The `shutil.copy()` function copies a file from one location to another.