top of page
Prostate Gland releases PSA molecules (15).png

WORKING WITH FILES

Problem:

Given:  A file containing at most 1000 lines.

​

Return: A file containing all the even-numbered lines from the original file. Assume 1-based numbering of lines.

​

Sample Dataset: 

​

Bravely bold Sir Robin rode forth from Camelot

Yes, brave Sir Robin turned about

He was not afraid to die, O brave Sir Robin

And gallantly he chickened out

He was not at all afraid to be killed in nasty ways

Bravely talking to his feet

Brave, brave, brave, brave Sir Robin

He beat a very brave retreat

​

Sample Output:  

​

Yes, brave Sir Robin turned about

And gallantly he chickened out

Bravely talking to his feet

He beat a very brave retreat

Solution:

Since genetic data is often stored in files, being able to work with files effectively is essential. Here's a useful tutorial getting into the nitty gritty of files.

​

First the file is accessed, in the read mode, and stored into a variable using the open method:

​

< >

file = open("input.txt", "r")

Then using the readlines() method, the file is read line-by-line and each odd line is stored into a list variable called lines, then all the list items are joined and printed:

< >

file = open("input.txt", "r")

lines = file.readlines()[1::2]

print("".join(lines))

Output:

Yes, brave Sir Robin turned about

And gallantly he chickened out

Bravely talking to his feet

He beat a very brave retreat

Copy and paste the output you get from running your code on the sample data onto the Rosalind answer terminal and submit. Annnd get yourself a cookie!

Subscribe to my mailing list and never miss a blogpost or new puzzle!

  • White Instagram Icon

Thanks for submitting!

bottom of page