Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

5. File Filter Write a program that reads a file and filters it, writing only certain lines to another file. write a program that asks

5. File Filter

Write a program thatreadsa file and "filters" it,writingonly certain lines to another file.

write a program that asks the user for three things:

  • input file name
  • output file name
  • a search string to look for lines that contain it

Read the input file, and then for each line that contains the search string, write that line to the output file.

Extensions :

  • Get your program to search for lines that start with the search string.
  • Python has a very helpful string method for this:startswith.
  • "hello".startswith("he") # this is True
  • E.g. Lindsay starts a lot of sentences with "So". So, if you had atranscript fileof one of his lectures and searched for "So", you could make a new file that contained those sentences.
  • Filter in other ways (not based on a user string), like lines that start with numbers or vowels or white space, etc.

Interesting Examples:

You would need tostrip()the lines to account for indenting in some of these.

  • The practical instructions file you are reading now is a "Markdown" text file. The headings all start with '#'.
  • If the user chose this file and searched for '#', then the output file would contain all of the headings.
  • Similarly, HTML headings are

    ,

    etc. so you could filter/strip those.

  • Python comments use#or""", so why not try getting your program to extract just the comments.

Note:

  • You know if you have to refer to the filename (literal) more than once, then it should be a... CONSTANT,
  • The above is also an example of DRY - don't repeat yourself with a function that is really similar to one you already have,
  • You know every time you open a file, you should close it as soon as you're finished,
  • You know your names must be meaningful,

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Introduction to Wireless and Mobile Systems

Authors: Dharma P. Agrawal, Qing An Zeng

4th edition

1305087135, 978-1305087132, 9781305259621, 1305259629, 9781305537910 , 978-130508713

More Books

Students also viewed these Programming questions