简体   繁体   中英

can any one help figure this out using python?

  1. Write a function that takes three arguments: a file-to-read, a file-to-write, and a word (string). It then reads lines from the text file-to-read and writes out only those lines containing the word into the file-to-write.
    • Sample input/output files attached at the end of this document.
    • Sample function call: selectlines(“problem3.txt","problem3write.txt","organic")
    • Attach output files for three different words. You may use your own input file, in which case, attach the input file together with your other submission files.

Here is some sample code:

def selectline(readfile,writefile,word):
    readfile=open('problem3.txt','r')
    lines=infile.read()
    infile.close()
    index=0
    while index<len(lines):
        lines[index]=str9lines[index]
        for word in lines:
            transfer=lines

Here is a hint for you to get you a bit further:

for line in infile:
    if text in line:
         outfile.write(line)

What you're currently doing is iterating the file character-by-character; you do not want to do that.

Instead, you can iterate a file line by line this way:

for line in open('myfile.txt'):
    ...

and then you can check whether a line contains a certain string by doing:

if 'organic' in line:
    ...

and write those lines that you need:

outfile.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