【问题标题】:Python 3 Self replicating file into random directory - then running filePython 3自我复制文件到随机目录 - 然后运行文件
【发布时间】:2014-12-05 03:44:28
【问题描述】:
我有一个有趣的小脚本,我想在一个随机目录中复制它自己 - 然后运行它自己的副本。
我知道如何使用 (hacky) 运行文件:
os.system('Filename.py')
而且我知道如何使用穿梭机复制文件 - 但我被困在随机目录中。也许如果我能以某种方式获得所有可用目录的列表,然后从列表中随机选择一个 - 然后从列表中删除该目录?
谢谢,
技术矩阵
【问题讨论】:
标签:
python
python-3.x
random
replicate
【解决方案1】:
您可以获取所有目录和子目录的列表,并随机打乱如下:
import os
import random
all_dirs = [x[0] for x in os.walk('/tmp')]
random.shuffle(all_dirs)
for a_dir in all_dirs:
print(a_dir)
# do something witch each directory, e.g. copy some file there.
【解决方案2】:
可以获取目录列表,然后随机选择:
import os
import random
dirs = [d for d in os.listdir('.') if os.path.isdir(d)]
n = random.randrange(len(dirs))
print(dirs[n])
【解决方案3】:
如果您使用的是 Mac,根目录附近有相当多的隐藏和受限目录。您可能会遇到可读性和可写性错误。解决这个问题的一种方法是遍历可用目录并使用 os 模块对所有不存在的内容进行排序。
之后,您可以使用 random.choice 模块从该列表中选择一个随机目录。
import os, random
writing_dir = []
for directory in os.listdir():
if os.access(directory, W_OK) # W_OK ensures that the path is writable
writing_dir.append(directory)
path = random.choice(writing_dir)
我现在正在编写一个类似的脚本。