开发者

Python Script to sort and rename files - Removes duplicates

I've written a small script that I needed to rename and sort files in the same folder where the script is. It renames the files into integers (1, 2, 3, 4, ...) based on the last modification of files:

import os
import sys
def gtime(nam):
    return os.path.getmtime('./'+nam)
files = os.listdir('.')
files.remove(str(sys.argv[0])[2:])
files = sorted(files, key=gtime)
for fi in range(len(files)):
    os.rename('./'+files[fi], './'+str(fi+1))

That was the best I've come up with to do so... The problem is when there's a duplicate开发者_运维百科 (e.g. a file already named 1, maybe from a previous sort) it just removes it.. How can I prevent this from happening?? Is there any modification I can do to the code or a better alternative way???


So here's an example that will copy to a subdirectory and avoid copying your script's .pyc file as well.

import os, sys
from os.path import exists, isfile, getmtime, join as pjoin
from shutil import copyfile

targetdir='process'
stub='inputfile'

if not exists(targetdir):
  os.mkdir(targetdir)

files = [ x for x in os.listdir('.') if isfile(pjoin('.',x)) and not x.startswith(sys.argv[0]) ]
pad = len(files)/10 + 1
for i,f in enumerate(sorted(files,key=lambda x: getmtime(pjoin('.',x)))):
  copytarget = pjoin('.',targetdir,"%s-%0.*d" % (stub,pad,i))
  print "Copying %s to %s" % (f,copytarget)
  copyfile(f,copytarget)


You can't rename one file after the other, as you might overwrite already sorted files during the process. You can however use temporary names first and then rename the files to their final names in a second pass:

import os
import sys
def gtime(nam):
    return os.path.getmtime('./'+nam)
files = os.listdir('.')
files.remove(str(sys.argv[0])[2:])
files = sorted(files, key=gtime)
for fi, file in enumerate(files):
    os.rename(file, str(fi+1)+".tmp")
for fi in range(len(files)):
    os.rename(str(fi+1)+".tmp", str(fi+1))

(untested)


import os.path
for fi in range(len(files)):
    if os.path.exists(str(fi+1)):
        print("Prevent that from happening") # whatever you want to do here
    else:
        os.rename(files[fi], str(fi+1))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜