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

tag5nh1u  于 2023-03-05  发布在  其他
关注(0)|答案(1)|浏览(153)

我有一个文件夹中的csv文件。我需要分开的csv文件从对方的基础上,如果一个特定的话,出现在文件中或没有。
编辑:原始代码被删除,因为它是不是反正工作。

vu8f3i0k

vu8f3i0k1#

如果有人想解决同样的问题:

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")

相关问题