0

スクリプトと同じフォルダー内のファイルの名前を変更して並べ替える必要がある小さなスクリプトを作成しました。ファイルの最後の変更に基づいて、ファイルの名前を整数(1、2、3、4、...)に変更します。

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))

それは私がそうするために思いついた最高でした...問題は、重複がある場合(たとえば、すでに1という名前のファイル、おそらく以前の種類のもの)、それを削除するだけです..これを防ぐにはどうすればよいですか? ?? コードにできる変更や、より良い代替方法はありますか?

4

3 に答える 3

2

.pycしたがって、サブディレクトリにコピーし、スクリプトのファイルもコピーしないようにする例を次に示します。

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)
于 2011-09-01T11:10:35.117 に答える
1

処理中に既にソートされたファイルを上書きする可能性があるため、ファイルの名前を次々に変更することはできません。ただし、最初に一時的な名前を使用してから、2回目のパスでファイルの名前を最終的な名前に変更することができます。

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))

(未テスト)

于 2011-09-01T09:27:00.613 に答える
0
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))
于 2011-09-01T09:23:55.353 に答える