简体   繁体   中英

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 . The output.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 ie

line2
line5
line8
line11

Any help or tips would be greatly appreciated!

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM