Saving remaining lines to file

informedmoon

I have a file I read and if the line in file contains "something" it will save the file to another file and if then I am trying to save lines that doesn't contain it to a different file but it doesn't work. Any help is appreciated. I am still a beginner in Python, so sorry if I am missing something silly.

with open("my.txt", errors='ignore') as f:
    lines = [l for l in f if "findme" in l]
    nolines = [l for l in f if "findme" not in l]
    with open("save.txt", 'a') as fi:
       for listitem in lines:
         fi.write(listitem)
    with open("remaining.txt", 'a') as fu:
       for listfail in nolines:
         fu.write(listfail)
norok2

The problem is that after the first looping through the lines of the file, your file pointer points at the end of the file. One way to solve your issue is to set the pointer back to the beginning with file.seek(0), e.g.:

with open("my.txt", errors='ignore') as f:
    lines = [l for l in f if "findme" in l]
    f.seek(0)  # reset the file pointer position to the beginning
    nolines = [l for l in f if "findme" not in l]
    with open("save.txt", 'a') as fi:
       for listitem in lines:
         fi.write(listitem)
    with open("remaining.txt", 'a') as fu:
       for listfail in nolines:
         fu.write(listfail)

However, a better approach to the problem is to loop through the lines only once and write the lines on the go:

with open('my.txt', 'r', errors='ignore') as src_file, \
        open('save.txt', 'a') as tgt1_file, \
        open('remaining.txt', 'a') as tgt2_file:
    for line in src_file:
        print(line, file=tgt1_file if 'findme' in line else tgt2_file, end='')

this is shorter, clearer and more efficient both computation-wise (presumably faster, but have not tested) and memory-wise (as there is no need to create potentially large intermediate lists).

Note that the use of print() here, makes this code actually run somewhat slower than the original approach. This can be easily fixed by reverting to file.write():

with open('my.txt', 'r', errors='ignore') as src_file, \
        open('save.txt', 'a') as tgt1_file, \
        open('remaining.txt', 'a') as tgt2_file:
    for line in src_file:
        (tgt1_file if 'findme' in line else tgt2_file).write(line)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Saving outputs (some lines in a file)

Saving Number of Lines in File as a Variable in Batch File

Reading the remaining lines of a file after searching for a word in the file

saving lines to file based on condition pandas python

groovy saving lines from file into collection

Saving df into txt file breaks up lines

Saving dataframe after text lines in .txt file

Unable to read the next and remaining lines in a csv file in Java

How to replace lines depending on the remaining text in file using PowerShell

How to delete or skip a list of lines in a text file and print the remaining lines in a new text file?

How to add alternating blank lines when saving csv file in Pandas

Not saving lines when writing to CSV file using for-loop

Extra blank lines in markdown file after submitting and saving in Django

Extra empty lines appear when saving the XML file

How to test if a string exists in a file and if so, check the remaining lines in the file for another string with bash shell

How to delete rows having bad error lines and read the remaining csv file using pandas or numpy?

Powershell - Capturing all lines between two values and saving the Captured lines to a file that Excel can read

grep not saving all lines

When saving scraped item and file, Scrapy inserts empty lines in output csv file

File not saving, or not

Prevent atom editor from deleting last blank lines when saving a file

Extracting lines from another file and saving unique fields in separate files in python

Java, write in file by saving the old inputs and adding the new inputs in new lines

Title with lines filling remaining space on both sides

How to store the remaining lines excepted the choosen one?

awk exact variable match, print remaining lines

awk: skip number of lines and apply a script on the remaining

My .gz/.zip file contains a huge text file; without saving that file unpacked to disk, how to extract its lines that match a regular expression?

Bash: capture the remaining lines after a fixed amount of lines

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive