Search code examples
pythonpython-2.7readlines

readlines from iterating through an array and writelines to a new file


bad_list is an array that is returned from a different function, returns the line numbers of rows that are problematic and need to be looked at more closely

e.g. array([ 1, 3, 4, 27, 50, 99], dtype=int64)


The idea is to read test.txt, and make a new test_badlines.txt which only contains the problematic lines as specified in bad_list


Here is what I have so far, the print line works but the writelines only spits out 1 line when it should be 6 lines

for rows in bad_list:
    filename = 'C:\\Users\\Username\\Downloads\\test.txt'
    bad_filename = str(filename)[:-4] + '_badlines.txt'
    with open(filename) as f,  open(bad_filename, 'w') as wt: 
        lines = f.readlines()
        #print lines[rows]
        wt.writelines(lines[rows])

Solution

  • lines is a plain list, and plain lists can't be indexed by a sequence of indices to look up. The simplest solution here is to make a generator expression that pulls out the lines you're concerned with, replacing:

    wt.writelines(lines[rows])
    

    with:

    wt.writelines(lines[row] for row in bad_list)
    

    Assuming bad_list is the array you described, you drop the outer for loop entirely; you don't want to open the input and output files over and over once per row, just once total.