【问题标题】:Unable to read the output file in python无法在python中读取输出文件
【发布时间】:2015-09-09 14:32:15
【问题描述】:

无法读取输出文件。代码看起来很完美,但我既没有得到期望的结果,也没有得到错误。请帮我解决这个问题

注意:我在打印时得到的结果是空格

with open("D:/txt_res/RahulChoudhary.txt") as infile, open ("x", 'w') as outfile:

    copy = False

    for line in infile:

        if line.strip() == "Technical Skills":

            copy = True

        elif line.strip() == "Work Experience":

            copy = False

        elif copy:

            outfile.write(line)

            infile = open("x", 'r')

            contents = infile.read()

            print(contents)

【问题讨论】:

  • 为什么要在 for 循环中关闭 outfile?你需要'a'模式吗?
  • @AnandSKumar 既没有错误也没有被执行
  • 你能用 infile 更新问题吗?
  • 不要在循环中关闭outfile,否则写完一行就写不下去了。
  • @LittleQ 据我所知,我们必须关闭输出文件,以便写入函数正常运行并将输出写入'x'。

标签: python information-retrieval data-retrieval


【解决方案1】:

根据您在 cmets 中指定的要求,我更新了我的代码。它在每一行中搜索“技术技能”,一旦找到,就会启用写作 (copy)。一旦命中这一行,它将写入每一行,当找到具有“工作经验”的行时,它会停止处理。

with open("in.txt") as infile, open ("out.txt", 'w') as outfile:

    copy = False

    for line in infile:

        if line.strip() == "Technical Skills":
            copy = True

        if line.strip() == 'Work Experience':
            break

        if copy:
            outfile.write(line)

fh = open("out.txt", 'r')
contents = fh.read()
print(contents)

鉴于此输入:

Introduction
I'm me, I'm not sane, I do reckless things most of the time, and I have a
very hard time keeping focused on tasks.

Technical Skills
- I have this skill
- and this skill
- I suck at these skills
- but I'm very good at this, that and the other too

Work Experience
2001 - 2010 Senior Network Engineer
2010 - 2015 Senior Toilet Cleaner

它会产生这个输出:

Technical Skills
- I have this skill
- and this skill
- I suck at these skills
- but I'm very good at this, that and the other too

如果您不想在输出中出现“技术技能”行,请在 copy = True 行之后直接添加一行 continue

【讨论】:

  • 我仍然没有得到所需的输出。当我在 spyder 中输入时,我得到了空格,如果我在 python.exe 中输入代码,那么我会得到一些数字作为输出,而我的输出必须是文本。
  • 好吧,考虑到您没有发布任何原始输入数据,这一定会发生。这个脚本所做的就是读取一个文件并循环它。如果文件中的某行包含“技术技能”,它将将该行写入输出文件。输入文件完成后,将打印输出文件。如果输入文件中没有“技术技能”,则输出文件将为空白,并且不会打印任何内容。如果您告诉我们您的输入是什么以及您希望输出什么确切,那真的很有帮助。
  • 输入文件是一份简历,标题为“技术技能”、“工作经验”等,我想在这里实现的是,从技术技能到工作经验剥离数据。如果我给出一个输出路径并在该路径中创建一个文本文件,我会得到结果,如此处所述->“with open("D:/txt_res/RahulChoudhary.txt") as infile, open("D: /txt_res/sample.txt", 'w') 作为输出文件:"
  • 但我不想每次都手动创建路径并创建一个文本文件然后保存输出,而是我想自动运行它。这就是为什么我想在将输出保存到文本或 csv 之前将输出保存到像“x”这样的变量中,因为我必须做进一步的分析。
  • 我已经在我的回答中更新了我的代码,提供了更多您需要的内容。
【解决方案2】:

首先,循环应该是:

for line in infile:

接下来,正如 Christopher Shroba 和其他人所提到的,您不应该在 for 循环中处理文件的打开/关闭。 “with”关键字是一个处理程序,因此它将处理打开和关闭文件。只需照原样写下该行即可。

这也适用于 infile。 “with”是处理它,所以你不需要手动打开或关闭它。

【讨论】:

  • 谢谢,我已经更新了我的代码。但我仍然没有得到输出,我得到空格或一些数字
猜你喜欢
  • 2017-06-12
  • 2017-05-11
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
  • 2023-03-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多