LoginSignup
4

More than 5 years have passed since last update.

Python覚書:テキスト参照して、対象ファイルをコピーしつつファイル名を編集する

Posted at

ファイル名を取得

対象ファイルがパス情報であったため、あらかじめファイル名のみを取得。

os.path.basename
file_name = os.path.basename(txt_fle_line)[:-1]

XCOPY

一時的に「subprocess.call」でXCOPYを利用もしてみたけど、
moveもする必要がでてきたので、汎用性を考えてshutilを使うことに。

subprocess.call
import subprocess
subprocess.call("xcopy %s %s /D /K /R /Y /C /V /E"%(file_path, send))

更新時間

更新時の新しいものを採用ということで、時間を取得して比較した。

shutil.py
        if os.path.exists(rename_file) :

            copy_date = os.stat(rename_file).st_mtime
            org_date = os.stat(file_path).st_mtime

            if copy_date < org_date:
                print "%s copy... %s" %(send, grid_name)
                shutil.copy2(file_path, rename_file)

        else:

テキスト参照して、対象ファイルをコピーしつつファイル名を編集するスクリプト。

copy_target.py
import os
import shutil
from datetime import datetime as dt

txt_file = open(r"copy_target.txt","r")

for target_line in txt_file:

    if target_line == '\n':
        break

    target_cl = target_line[:-1].split(',')

    file_path = target_cl[0].strip('"')
    file_name = target_cl[1].strip('"')

    grid_cl = file_name.split('_')

    if len(grid_cl) == 6:

        photo = grid_cl[0]
        area = grid_cl[1]
        b_cl = grid_cl[2]
        b_rw = grid_cl[3]
        b_no = grid_cl[4]
        flg = grid_cl[5]

    grid_name = area + b_cl + b_rw
    send = r'G:\grid\\' + area + '\\' + grid_name

    if os.path.isdir(send) :

        rename_file = send +'\\'+ file_name

        if os.path.exists(rename_file) :

            copy_date = os.stat(rename_file).st_mtime
            org_date = os.stat(file_path).st_mtime

            if copy_date < org_date:
                print "%s copy... %s" %(send, grid_name)
                shutil.copy2(file_path, rename_file)

        else:
            print "%s copy new... %s" %(send, grid_name)
            shutil.copy2(file_path, rename_file)

    else:
        is_not_file = open(r"D:\python\file_serch\target_work\is_not_GRID.txt", "a+")
        is_not_file.write(file_path + "," + file_name + "," + "no path" + "\n")

        is_not_file.close()

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4