0

イメージの名前を変更する際のデータ移行に役立つスクリプトを作成します。filename内部 for ループ内から変数にアクセスしようとすると、単に印刷されているようです.DS_Store

たとえば、コメント行を参照してください。

#!/usr/bin/env python
import os
import csv

FILE_PATH = '/Users/admin/Desktop/data-migration/images/product'
COUNT = 0

with open('paths_formatted.csv') as csvfile:
    reader = csv.reader(csvfile)

    # Walk the tree.
    for root, directories, files in os.walk(FILE_PATH):

        for filename in files:

            # Join the two strings in order to form the full filepath.
            filePath = os.path.join(root, filename)

            #print(filePath) - this results in the actual file path

            for row in reader:

                #print(filePath) - this results in .DS_Store

                oldFilePath = row[1].strip()
                displayName = row[0].strip()
                colour = row[2].strip()


                if " " in colour:
                    colour = colour.replace(" ", "-")

                slashIndex = oldFilePath.rfind("/")         
                oldFileName = oldFilePath[slashIndex+1:]

                if oldFileName == filename:

                    number = 1;
                    newFileName = displayName + "_" + colour + "-" + str(number) + ".jpg"
                    while os.path.exists(FILE_PATH + leadingPath + newFileName):
                        number = number + 1
                        newFileName = filePath, displayName + "_" + colour + "-" + str(number)

                    os.rename(newFileName)
                    COUNT = COUNT+1

print(COUNT)

これはなぜでしょうか?

コメントに従ってコードを変更した後、結果をリストに保存するために、現在はfor root, directories, files in os.walk(FILE_PATH):実行されていません。

が存在することを確認し、FILE_PATHコンソールに出力しました。また、コンテンツがあることも確認しました。

私の新しいコードは次のとおりです。

#!/usr/bin/env python
import os
import csv

FILE_PATH = '/Users/admin/Desktop/data-migration/images/product'
COUNT = 0

productInfo = []

with open('paths_formatted.csv') as csvfile:
    reader = csv.reader(csvfile)

    for row in reader:
        productInfo.append(row)

for root, directories, files in os.walk(FILE_PATH):

    for filename in files:

        for info in productInfo:

            displayName = info[0]
            oldFilePath = info[1]
            colour = info[2]

            slashIndex = oldFilePath.rfind("/")         
            oldFileName = oldFilePath[slashIndex+1:]

            if " " in colour:
                colour = colour.replace(" ", "-")

            if oldFileName == filename:

                number = 1;
                newFileName = displayName + "_" + colour + "-" + str(number) + ".jpg"

                while os.path.exists(FILE_PATH + leadingPath + newFileName):
                    number = number + 1
                    newFileName = filePath, displayName + "_" + colour + "-" + str(number) + ".jpg"

                os.rename(newFileName)
                COUNT = COUNT + 1

print(COUNT)
4

0 に答える 0