Skip to content

Instantly share code, notes, and snippets.

@Xiaorui-Huang
Last active October 17, 2023 18:43
Show Gist options
  • Select an option

  • Save Xiaorui-Huang/b5064bbdc0de5522838be7bb9034856e to your computer and use it in GitHub Desktop.

Select an option

Save Xiaorui-Huang/b5064bbdc0de5522838be7bb9034856e to your computer and use it in GitHub Desktop.
Remove Random files in Android folder
import os
import random
import subprocess
import argparse
def get_file_list(directory_path: str) -> list[str]:
"""
use adb to get a list of files in the specified directory on the android device.
"""
cmd = ['adb', 'shell', 'ls', directory_path]
result = subprocess.check_output(cmd)
return [line.strip() for line in result.decode('utf-8').splitlines() if line.strip()]
def remove_random_files(directory_path: str, percentage: float, dry_run: bool = false, seed: int = none) -> none:
"""
remove the specified percentage of files from the directory randomly.
"""
if seed is not none:
random.seed(seed)
files = get_file_list(directory_path)
num_files_to_remove = int(len(files) * (percentage / 100.0))
# select random files to remove
files_to_remove = random.sample(files, num_files_to_remove)
for file in files_to_remove:
if dry_run:
print(f"[dry run] would remove: {directory_path}/{file}")
else:
print(f"removing: {os.path.join(directory_path, file)}")
cmd = ['adb', 'shell', 'rm', f"{directory_path}/{file}"]
subprocess.run(cmd)
def main() -> none:
parser = argparse.argumentparser(description="remove a specified percentage of files randomly from a given directory on an android device.")
parser.add_argument("directory_path", default="/sdcard/download/videodownloader", type=str, help="directory path on the android device.")
parser.add_argument("percentage", default=50, type=float, help="percentage of files to remove (0 to 100).")
parser.add_argument("--dry-run", "-n", action="store_true", help="simulate the removal without actually removing files.")
parser.add_argument("--seed", "-s", type=int, help="seed for random number generator for reproducibility.")
args = parser.parse_args()
# ensure the percentage value is valid
if 0 <= args.percentage <= 100:
remove_random_files(args.directory_path, args.percentage, args.dry_run, args.seed)
if not args.dry_run:
print(f"{args.percentage}% of files from {args.directory_path} have been removed.")
else:
print("invalid percentage value. it should be between 0 and 100.")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment