0
with open(data_path) as f:
    content = f.readlines()
content = [x.strip() for x in content]

The following code will read every single line and insert it into a list. But the code i want should read the first line and skip the second then read the third or simply adjust content to "remove" values with odd indices number.

Jimmy
  • 313
  • 1
  • 4
  • 9
  • Is it an upgrade? If you use that method you're essentially iterating over the lines of the file **twice**. Wouldn't it be better to read the lines you want and store them all in just one pass? – Elfen Dew Nov 28 '17 at 08:31
  • Possible duplicate of [How do I get python to read only every other line from a file that contains a poem](https://stackoverflow.com/questions/30551945/how-do-i-get-python-to-read-only-every-other-line-from-a-file-that-contains-a-po) – Elfen Dew Nov 28 '17 at 08:32

2 Answers2

6

Simply set step equals to 2 in your list comprehension

content = [x.strip() for x in content[::2]]
vishes_shell
  • 22,409
  • 6
  • 71
  • 81
1

As you stated your problem:

should read the first line and skip the second then read the third

You can do all things in one line :

One line solution:

print([item.strip() for index,item in enumerate(open('file.txt','r')) if index % 2 == 0])

above list comprehension is same as:

final_list=[]
for index,item in enumerate(open('file.txt','r')):
    if index % 2 == 0:
        final_list.append(item.strip())
Aaditya Ura
  • 12,007
  • 7
  • 50
  • 88
  • @vishes_shell yea i know , but python take care of that generally.Some Pythons will close files automatically when they are no longer referenced, while others will not and it's up to the O/S to close files when the Python interpreter exits. – Aaditya Ura Nov 28 '17 at 10:06
  • Sure it does, but usually we might use same file over and over, and without closing it, or without using context manager we won't be able to do anything. – vishes_shell Nov 28 '17 at 10:08
  • 1
    @vishes_shell yea , but i just shown one line solution, but i agree with you :) – Aaditya Ura Nov 28 '17 at 10:10