简体   繁体   中英

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

eg 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])

lines is a plain list , and plain list s 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.

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