【问题标题】:Take input from excel and data need to be removed from text file [duplicate]从excel中获取输入,需要从文本文件中删除数据[重复]
【发布时间】:2021-06-28 15:49:25
【问题描述】:

我在 excel 文件 (data.xlsx) 中的以下数据比 6000 rows 多,并且我的 ubuntu 系统中有许多文本文件。

文本文件目录结构:-

/home/user/excel/report/ML_PROJECT_APPLICATION_WRITE.txt
/home/user/excel/report/folder-1/ML_PROJECT_APPLICATION_OPEN.txt
/home/user/excel/report/folder-1/filepath/ML_PROJECT_UBUNTU_OPEN.txt
/home/user/excel/report/folder-2/ML_PROJECT_CENTOS_WRITE.txt
/home/user/excel/report/folder-3/ML_PROJECT_RHEL_WRITE.txt

文本文件格式如下之一,

ML_PROJECT_APPLICATION_WRITE.txt

# //DEPOT/ABCD/PROJECT/Jerd
# Permission: WRITE

dreac.leoson
ritu.bhangale
makyen
markerikson.s
bernardo.pereira 
elitezen

文本文件的文件名与 Excel 工作表的 D 列匹配。对于每一行,我想根据D 列搜索文本文件,并且需要查看H 列中的用户ID,如果该特定行匹配的文本文件中存在用户ID,则需要user-id从该文本文件中删除。需要帮助以自动化方式实现这一目标。谢谢!

【问题讨论】:

    标签: python excel linux shell


    【解决方案1】:

    首先,将data.xlsx 导入pandas.DataFrame 并创建dict 以映射文件名和用户ID:

    import pandas as pd
    data = pd.read_excel("data.xlsx")
    d = dict(zip(data["File Name"], data["User-ID"]))
    

    使用自定义函数返回文件的路径(带有子目录):

    import os
    def find(name):
        for root, _, files in os.walk("/home/user/excel/report"):
            if name in files:
                return os.path.join(root, name)
    

    然后,遍历dict 并根据需要转换您的文件。首先,读取文件。然后,如果存在,则删除用户 ID 并写回文件。

    for file in d:
        fullname = find(f"{file}.txt")
        if fullname is not None:
            with open(fullname, "r") as f:
                contents = f.read().strip()
        
            with open(fullname, "w") as f:
                f.write(contents.replace(d[file], ""))
    

    注意,如果您的文件位于不同的目录中,请确保在 pd.read_excelopen 中指定整个文件路径。

    【讨论】:

    • not_speshal,谢谢。文件位于不同的目录中,例如 /home/user/excel/report/
    • 即使这也递归地处理存在于/home/user/excel/report/ 目录子目录中的text 文件?
    • home/user/excel/report/子目录下找不到text files。你能帮我在它的子目录中搜索吗?
    • 用您的文件夹结构和每个文件的位置更新您的问题。
    • 我用text files 的文件夹结构更新了问题。根据data.xlsx 文件,它需要在/home/user/excel/report/ 文件夹及其子文件夹中搜索/找到text file
    猜你喜欢
    • 1970-01-01
    • 2018-02-24
    • 1970-01-01
    • 2016-02-08
    • 2013-12-21
    • 1970-01-01
    • 1970-01-01
    • 2010-11-17
    • 2013-03-27
    相关资源
    最近更新 更多