3

と のようなフォルダが複数folder.0ありますfolder.1。各フォルダ内には 1 つのファイル ( 'junk') があり、そのファイルをコピーして、現在存在するフォルダ名.0またはその一部に名前を変更します。 これが私がやろうとしていることです:.1

inDirec = '/foobar'
outDirec = '/complete/foobar'


for root, dirs,files in os.walk(inDirec):
    for file in files:
        if file =='junk'
            d = os.path.split(root)[1]
            filename, iterator = os.path.splitext(d)  # folder no. captured
            os.rename(file, iterator+file) # change name to include folder no.
            fullpath = os.path.join(root,file)
            shutil.copy(fullpath,outDirec)

これは以下を返します:

os.rename(file,iterator+file)
OSError: [Errno 2] No such file or directory

os.rename を使用する必要があるかどうかさえわかりません。それらを引き出して1つのディレクトリにコピーしたいだけですfiles == 'junk'が、それらはすべてまったく同じ名前です。したがって、同じディレクトリに存在できるように、名前を変更する必要があります。何か助けはありますか?

アップデート

    for root, dirs,files in os.walk(inDirec):
    for file in files:
        if file =='junk'
            d = os.path.split(root)[1]
            filename, iterator = os.path.splitext(d)  # folder no. captured
            it = iterator[-1] # iterator began with a '.'
         
            shutil.copy(os.path.join(root,file),os.path.join(outDirec,it+file))
4

1 に答える 1

7

問題は、プログラムが起動時に名前変更操作に作業ディレクトリを使用していることです。os.rename()の引数として、完全な相対パスまたは絶対パスを指定する必要があります。

交換:

os.rename(file, iterator+file)
fullpath = os.path.join(root,file)
shutil.copy(fullpath,outDirec)

と(移動したい場合):

os.rename(os.path.join(root, file), os.path.join(outDirec, iterator+file))

または(コピーしたい場合):

shutil.copy(os.path.join(root, file), os.path.join(outDirec, iterator+file))

注:宛先ディレクトリはすでに存在している必要があります。そうでない場合は、作成するためのコードが必要になります。

于 2012-10-05T13:20:44.820 に答える