swapname.py - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: General (https://python-forum.io/forum-1.html) +--- Forum: Code sharing (https://python-forum.io/forum-5.html) +--- Thread: swapname.py (/thread-15671.html) |
swapname.py - Skaperen - Jan-27-2019 a little script i often use: swapname.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- from __future__ import print_function from os import lstat,rename from sys import argv,stderr,stdout import time if len(argv)!=3: print('need exactly two filenames to swap',file=stderr) exit(2) a,b=argv[1:3] if a==b: print(repr(a),'is given twice',file=stderr) exit(2) e=0 try: r=lstat(a) except: print('file',repr(a),'does not exist',file=stderr) e=1 try: s=lstat(b) except: print('file',repr(b),'does not exist',file=stderr) e=1 if e: exit(1) if (r.st_dev,r.st_ino)==(s.st_dev,s.st_ino): print(repr(a),'and',repr(b),'are the same object',file=stderr) exit(1) u='swapname-'+hex(int(time.time()*5000000))[-14:] print(repr(a),'<-->',repr(b),end='') stdout.flush() rename(a,u) rename(b,a) rename(u,b) print() exit(0) |