Unable to read the output file in python

454 views Asked by At

Unable to read the output file. The code seems perfect, but neither im getting desire result nor im getting an error. Please help me on this

Note: I'm getting the result as blank space as i print

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

There are 2 answers

7
stevieb On BEST ANSWER

Based on your specified requirements in the comments, I've updated my code. It searches for "Technical Skills" in each line, and once found, enables writing (copy). It will write every line once this one is hit, and when a line with "Work Experience" is found, it stops processing.

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)

Given this input:

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

It will produce this output:

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

If you don't want the "Technical Skills" line in the output, put a line with continue directly after the copy = True line.

1
Rob Foley On

First off, the loop should be:

for line in infile:

Next, as Christopher Shroba and others mentioned, you should not handle the opening/closing of the file in the for loop. The "with" keyword is a handler, so it will deal with opening and closing the files. Just write the line to it as you are already.

This goes for the infile as well. "With" is handling it, so you do not need to open or close it manually.