【问题标题】:Python - match string to csv value, then extract adjacent columnPython - 将字符串匹配到csv值,然后提取相邻列
【发布时间】:2019-12-11 15:26:35
【问题描述】:

我对 Python 很陌生,所以请原谅我恶心的格式或糟糕的优化。

我正在尝试编写一个脚本来根据文件名称将文件分类到新文件夹中。 为了将他们的名字与正确的新位置匹配,我有一个包含两列的 csv 文件;第一个是文件名的一部分,第二个是它所属的正确文件夹。

到目前为止,我已经编写了所有内容以提取我需要的文件名部分,但现在我不知道如何将我拥有的字符串与 csv 中的值匹配,然后提取相邻的列。

这是我目前所拥有的:


import os
import csv

def openCSV(csvFile):
    file = open(csvFile)
    reader = csv.DictReader(file)
    data = list(reader)

    return data

def findDemoName(fileName):
    demoName = fileName[16:]
    demoName = demoName[:-11]

    return demoName

def moveFiles(sortingFile, sourceDirectory, destinationDirectory):
    sortingCSV = openCSV(sortingFile)
    srcDir = sourceDirectory
    destDir = destinationDirectory

    for filename in os.listdir(srcDir):
        name = findDemoName(filename)

        print(name)


# begin program
if __name__ == "__main__":
    # set the CSV used to sort the files
    fileToSortFrom = '<csv used for sorting>'
    inputDirectory = '<where the files are located>'
    outputDirectory = '<where I want to move the files>'


    moveFiles(fileToSortFrom, inputDirectory, outputDirectory)

现在它只是打印文件名的提取部分并打印出来,这样我就可以确保它正在做我想做的事情。

所以我的下一步是 1.将文件名的提取部分与csv第一列中的匹配值匹配 2.取匹配项旁边的值,用它来完成要移动到的文件的目标路径

我找到了这个线程 match names in csv file to filename in folder,但我不明白 csv 匹配到的答案在哪里。

如果我需要澄清一些问题,请告诉我,我会的。

提前感谢您的阅读:)

 

编辑:

我试图通过这个偶然发现,这就是我目前所拥有的:

import os, shutil
import csv

def openCSV(csvFile):
    file = open(csvFile)
    reader = csv.DictReader(file)
    data = list(reader)

    return data

"""def createReader(csvFile):
    file = open(csvFile)
    reader = csv.DictReader(file)

    return reader"""

def extractDemoName(fileName):
    originalName = fileName
    demoName = fileName[16:]
    demoName = demoName[:-11]

    return demoName

def moveFiles(sortingFile, sourceDirectory, destinationDirectory, prefix, suffix):
    reader = openCSV(sortingFile)
    #reader = createReader(sortingFile)
    srcDir = sourceDirectory
    destDir = destinationDirectory
    column1 = 'DemographicName'
    column2 = 'DemographicTypeName'
    folder = ''

    for filename in os.listdir(srcDir):
        name = extractDemoName(filename)

        for row in reader:
            if row(column1) == name:
                folder = row(column2)
                destination = destDir + folder
                file = prefix + name + suffix

                shutil.copy(file, destination)

                print('Moved ' + file + ' to ' + destination)
            #else reader.next()



        print(name)


# begin program
if __name__ == "__main__":

    # set the CSV used to sort the files
    fileToSortFrom = '<csv file>'
    inputDirectory = '<source path>'
    outputDirectory = '<destination path>'
    filePrefix = '<beginning text of files>'
    fileSuffix = '<ending text of files>'

    moveFiles(fileToSortFrom, inputDirectory, outputDirectory, filePrefix, fileSuffix)

但现在我收到以下错误:

Traceback (most recent call last):
  File "script.py", line 63, in <module>
    moveFiles(fileToSortFrom, inputDirectory, outputDirectory, filePrefix, fileSuffix)
  File "script.py", line 38, in moveFiles
    if row(column1) == name:
TypeError: 'collections.OrderedDict' object is not callable

【问题讨论】:

    标签: python string csv match filenames


    【解决方案1】:

    有问题(第38行)

    if row(column1) == name:
    

    应该是

    if row[column1] == name:
    

    我没有检查脚本中的任何其他逻辑 :)

    【讨论】:

    • 谢谢亚历克斯 :) 这有帮助!
    【解决方案2】:

    此脚本从您在方法move_filesfrom_dir 中传递的目录中读取文件。 它检查 from_dir 中的文件是否存在于 csv_file 中,如果存在,它会获取位置并将其移动到该目录。

    
    import os
    import csv
    import shutil
    
    
    def get_file_sorter_dict(csv_file):
        return dict(list(csv.reader(open(csv_file))))
    
    
    def move_files(csv_file, from_dir, to_dir):
        file_sorter_dict = get_file_sorter_dict(csv_file)
    
        for filename in os.listdir(from_dir):
            if file_sorter_dict.get(filename):
                # you can use the location to move the file from csv_file
                # move_to = file_sorter_dict.get(filename)
                # shutil.move(filename, move_to)
    
                # or you can use to_dir to move the file.
                shutil.move(filename, to_dir)
    
    
    if __name__ == "__main__":
    
        move_files('files_sorter.csv', '.', '../')
    
    

    我使用的 csv 看起来像:

    name, location
    "foo.txt","../"
    "baz.txt","../"
    
    
    

    【讨论】:

    • 嘿,感谢 thisshri 的回复。我用 csv 中的显式文件路径尝试了这个脚本,如下所示:name, location "C:/folder/file.pdf", "C:/folder/desintationfolder" "C:/folder/file2.pdf", "C:/folder/destinationfolder" 该脚本几乎立即运行,但实际上并没有做任何事情。
    • 问题是for filename in os.listdir(from_dir) 中的文件名只是文件的名称,而不是文件的位置,这就是为什么if file_sorter_dict.get(filename) 代码没有运行,因为它只需要名称该文件,而在您的情况下,您拥有文件位置。尝试解决这个问题,它会起作用。
    猜你喜欢
    • 2019-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-13
    • 2013-02-14
    • 2020-10-14
    • 1970-01-01
    • 2018-10-06
    相关资源
    最近更新 更多