user493989
user493989

Reputation: 1

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

Upvotes: 0

Views: 156

Answers (2)

Lie Ryan
Lie Ryan

Reputation: 64845

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)

Upvotes: 1

Lennart Regebro
Lennart Regebro

Reputation: 172259

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

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

Upvotes: 1

Related Questions