Python - 互相交换两个文件目录

时间:2017-08-13 00:55:48

标签: python filesystems file-rename

我有一个机器人,它的设置方式是从网站的前端接收命令,然后在机器人上运行命令。例如

if command == 'CF':
    os.system('aplay /home/pi/sound/wavycf.wav')

我需要将两个文件/images/hud.pngimages/special/hud.png交换到其他目录的东西....我希望这是有道理的

1 个答案:

答案 0 :(得分:0)

只需将一个置于临时位置,移动另一个,然后先从临时位置移动到最终位置

os.system("move /images/hud.png /images/special/hud.png.tmp")
os.system("move /images/special/hud.png /images/hud.png")
os.system("move /images/special/hud.png.tmp /images/special/hud.png")

或者每次使用python:

# load file 1 into buffer
data = ""
with open("/images/hud.png", "rb") as f:
    data = f.read()
# copy file 2 into file 1
with open("/images/special/hud.png", "rb") as f1:
    with open("images/hud.png", "wb") as f2:
        f2.write(f1.read())
# save file 1 from buffer
with open("/images/special/hud.png", "wb") as f:
    f.write(data)
# clear memory
del data