Python Forum

Full Version: swapname.py
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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)