Created
July 24, 2019 07:03
-
-
Save candlewill/dc69ba505c96ecfb2b3f6ec1453968c0 to your computer and use it in GitHub Desktop.
Random select N files with specified suffix, and copy to the target folder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# encoding: utf-8 | |
import os, sys | |
import glob | |
import random | |
Usage = "Random select N files with specified suffix, and copy to the target folder\n" \ | |
".py <source dir> <target dir> <suffix> <num files>" | |
os.system("export PYTHONIOENCODING=utf8") | |
os.system("export LC_ALL=en_US.UTF-8") | |
os.system("export LANG=en_us.UTF-8") | |
escaped_char = "()" | |
def main(): | |
if len(sys.argv) != 5: | |
print(Usage) | |
sys.exit() | |
source = sys.argv[1] | |
target = sys.argv[2] | |
suffix = sys.argv[3] | |
num_files = int(sys.argv[4]) | |
files = glob.glob(os.path.join(source, "*" + suffix)) | |
print("There are %d %s files in folder %s" % (len(files), suffix, source)) | |
random.shuffle(files) | |
files = files[:num_files] | |
print("start copy...") | |
os.makedirs(target, exist_ok=True) | |
for file in files: | |
basename = os.path.basename(file) | |
target_filename = os.path.join(target, basename) | |
for char in escaped_char: | |
file = file.replace(char, "\\" + char) | |
cmd = "cp %s %s" % (file.strip(), target_filename.strip()) | |
os.system(cmd) | |
print(cmd) | |
print("Copied %s files to %s" % (len(files), target)) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment