在文件夹中搜索所有 CSV 文件中的单词,并且只移动找到该单词的文件

问题描述 投票:0回答:1

我有一个装满 csv 文件的文件夹。 我需要根据以下内容将 csv 文件彼此分开, 文件中是否出现特定单词。

编辑:删除了原始代码,因为它无论如何都不起作用。

string csv file search move
1个回答
0
投票

万一有人想解决同样的问题:

    import os
    import shutil
    import pandas as pd
    
    location = "/home/any_location_you_want/"

    # This is the path where you want to search
    path = location

    # this is the extension you want to detect
    extension = '.csv'

    for file in os.listdir(location):
        filename = os.fsdecode(file)
        file_path = os.path.join(filename)
    
        if filename.endswith(".csv"):
            df = pd.read_csv(file, low_memory=False)
    
#If a .csv file was found we look at the column "sport" to check if the word "cycling" is in it.

#If so, the file will be moved to a cycling-folder

            if (df['sport']).str.contains('cycling').any():
                print("Cycling: ", filename)
                shutil.copy(os.path.join(location, filename), "/home/any_location/cycling")
                os.remove(os.path.join(location, file))

    #if the file has not been moved yet and it contains the word "running", it will be moved to a running-folder and removed from this folder.  

  
            if (df['sport']).str.contains('running').any():
                print("Jogging-File: ", filename)
                shutil.copy(os.path.join(location, filename), "/home/any_location_running")
                os.remove(os.path.join(location, file))
    
    print()
    print("ENDE")
© www.soinside.com 2019 - 2024. All rights reserved.