Fexyk
Fexyk

Reputation: 3

How would i put strings into an array from another text file (reading line by line) but only reading every other line

(in txt file)

line

line

notice that there's a blank line between line

I would want the array to look like: x = [“line”, “line”, “notice that there's a blank line between line”]

Upvotes: 0

Views: 83

Answers (2)

Tabaene Haque
Tabaene Haque

Reputation: 574

You can do it in this way -

with open("file_name.txt") as file:
    result = [line.rstrip() for line in file if line.rstrip()]
    print (result)

O/P: ['line', 'line', "notice that there's a blank line between line"]

Upvotes: 0

Eriall
Eriall

Reputation: 316

Try

txtFile = open("yourfile.txt").readlines()
x = [txtFile[i].strip() for i in range(len(txtFile)) if i % 2 == 0 ]

Edit: If you just want to remove blank lines try replacing the x variable line with

x = [txtFile[i] for i in range(len(txtFile)) if txtFile[i] != "\n"]

Upvotes: 2

Related Questions