下面的数据在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。需要帮助,以实现这一自动化的方式。谢谢!
发布于 2021-06-28 16:12:32
首先,将data.xlsx导入pandas.DataFrame并创建一个dict来映射文件名和用户ids:
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_excel和open中指定整个文件路径。
https://stackoverflow.com/questions/68166384
复制相似问题