userAD
userAD

Reputation: 83

Printing no output to a text file in python while reading specific lines

I want to print every third line (starting from line 2) from a file to a new file. The example of the file (line.txt) is

line1
line2
line3
line4
line5
line6
line7
line8
line9
line10
line11

The output will be

line2
line5
line8
line11

The script that I have written is

with open ('line.txt') as file:
    for line in file.read().split("\n")[1::3]:
        print (line)
        f = open('output.txt','w')
        f.write(line)
        f.close()

But nothing is being copied in the output.txt file. Theoutput.txt remains blank. Even if I print the line after running the script in python IDLE, the line returns blank ' '. But during running the script, the output is the desired output i.e.

line2
line5
line8
line11

Any help or tips would be greatly appreciated!

Upvotes: 0

Views: 839

Answers (3)

onno
onno

Reputation: 979

You are closing the output.txt file and opening it again every time in your loop. I would suggest to put these out of the loop:

with open('output.txt', 'w') as f:
    with open ('line.txt', 'r') as file:
        for line in file.readlines()[1::3]:
            print(line)
            f.write(line)

note: I also added +'\n to the write statement to include line endings in your output.txt

Edit: as @DeepSpace rightly noted you could better use with open() for both files and readlines() instead of read().split('\n'). Using with open() you don't need to remember to close it.

Upvotes: 1

Junior Mayta
Junior Mayta

Reputation: 31

the following script write in an file output.txt according your description I wish to print every third line (starting from line 2) from a file to a new file

output_file = open("output.txt", "a")
with open ('line.txt') as file:
    for line in file.readlines()[1::3]:
        output_file.write(line)
output_file.close()

I am using readlines() instead of read() becaute it reads a whole line instead of read a single string. Also I am using open file with "a" instead of "w" because the Appending mode allows you to append content in the file. With "w" you were overwriting each iteration of the loop. I hope it helps.

Upvotes: 0

ravishankar chavare
ravishankar chavare

Reputation: 503

with open ('line.txt') as file:
        f = open('output.txt','w')
        for line in file.read().split("\n")[1::3]:
            outputline=line
            f.write(outputline)
        f.close()

Upvotes: 0

Related Questions