简体   繁体   中英

How to write specific lines of a text to a new file?

I have a text file from which I want to find specific lines and write them to a new file. the text looks something like this:

1552311_a_at    NA  6.548202118 6.795958567 6.525295817 6.467153775  
1552312_a_at    NA  7.237622005 7.501887409 7.438287339 7.249551462 
1552334_at  NA  5.36199913  5.554097857 5.296649894 5.64695338  

I've done this before without many problems, but for some reason it won't work for me in this instance. I have a list of values I'm looking for in the text file to extract.

import fileinput 

x = open('file', 'r')
y = open('file_write', 'w')
z = [...,...,...] #list of values to search for in file given by user
def file_transform(filein,fileout,list):
    for i in list:
        for line in filein:
            if list[i] in line:
                fileout.write(line)

file_transform(x,y,z)

file.close()
file_write.close()

the script runs, but I end up with an empty new text file. I cannot understand where I'm going wrong.

You cannot cycle multiple times the same file without "rewinding", also you are misusing for cycle on list:

def file_transform(filein,fileout,z):
    for i in z:
        for line in filein:
            if i in line:
                fileout.write(line)
        filein.seek(0)

or, much better:

def file_transform(filein,fileout,z):
    for line in filein:
        for i in z:
            if i in line:
                fileout.write(line)

When you do for i in z i actually contains elements of list not indexes. For more information see this .

list is not a good name for any variable, as list is an object-type in python.

with open('file', 'r') as f:
    x = f.readlines() # this auto closes the file after reading, which is better practice

y = open('file_write', 'w')

def file_transform(filein, fileout, z):
    for line in filein:
        for i in z:
            if i in line:
                fileout.write(line)

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