解析大型excel文件并将结果写回分隔文本

2024-04-20 16:28:26 发布

您现在位置:Python中文网/ 问答频道 /正文

注意:既然问了我该怎么办<关于代码评审的问题是离题的,我在这里试试

我在一家跨国公司做IT实习生,有人给了我一个繁琐的任务,就是通过一个2500多列的excel报表文件来搜索不活跃的服务器

下面是该文件中的一个示例行:

enter image description here

然后,我得到了另一个excel文件,但这次只有DB代码(80+个)

我的任务是:

  • 浏览大报告文件
  • 通过数据库代码查找公司
  • 检查服务器是否处于活动状态,如果未处于活动状态,则将其标记为停用

当然,正如您所料,我被告知以电子表格的形式返回结果,格式如下:

Full name: Acme Inc. | Code: ACM | Active?: no | Decomm?: yes

Fulln name:, Code:, etc.是列标题。在这里,它们只是为了可读性

如果我手工做的话,我很可能会无聊死。但是!有Python,对吗

因此,我将报告中的一些列导出到以制表符分隔的文件中,并起草了以下内容:

def read_file_to_list(file_name):
    with open(file_name, 'r') as file_handler:
        stuff = file_handler.readlines()
    return [line[:-1] for line in stuff]


def make_dic(file_name):
    with open(file_name, 'r') as f:
        rows = (line.replace('"', "").strip().split("\t") for line in f)
        return {row[0]:row[1:] for row in rows}


def search(dic, ou_codes):
    c = 1
    for k, v in dic.items():
        for code in ou_codes:
            if v[0] == code:
                print("{}. Full name: {} | Code: {} | Active?: {} | Decomm?: {}".format(c, k, *v, "yes" if v[1] == "no" else "no"))
                c += 1


decomm_codes = read_file_to_list('decomm_codes.txt')
all_of_it = make_dic('big_report.txt')

search(all_of_it, decomm_codes)

吐出来的是:

1. Full name: Random, Inc | Code: RNDM | Active?: yes | Decomm?: no
2. Full name: Acme Inc.| Code: ACM | Active?: no | Decomm?: yes
3. Full name: Fake Bank, Ltd.  | Code: FKBNK | Active?: yes | Decomm?: no

问题:

在终端窗口中看起来很不错,但是如何将结果写回制表符分隔的文本文件中呢?所以看起来是这样的:

Acme Inc. ACM no yes

另外,出于好奇,有没有办法重构search方法,例如,一行代码?嵌套的列表理解仍然在我的学习列表中(双关语)

最后,这里是decomm_codes.txtbig_report.txt文件的内容

decomm_codes.txt文件:

RNDM
ACM
FKBNK

大报告.txt:

"Random, Inc"   RNDM    yes
Acme Inc.   ACM no
"Fake Bank, Ltd. "  FKBNK   yes

Tags: 文件nonameintxtforcodefull
1条回答
网友
1楼 · 发布于 2024-04-20 16:28:26

也可以简单地写入文件:

def search(dic, ou_codes):
    c = 1
    # open a file to write to
    with open ("output.tsv","w") as outfile:
        outfile.write( "#\tFull name\tCode\tActive\tDecomm\n")
        for k, v in dic.items():
            for code in ou_codes:
                if v[0] == code:
                    # create output line
                    outputline = "{}\t{}\t{}\t{}\t{}\n".format(
                                 c, k, *v, "yes" if v[1] == "no" else "no")
                    c += 1
                    outfile.write(outputline)
                    print("{}. Full name: {} | Code: {} | Active?: {} | Decomm?: {}".format(
                          c, k, *v, "yes" if v[1] == "no" else "no")) 

相关问题 更多 >