0

I have a txt file that contains names which are separated by lines but with some empty lines. When I execute the following code, every second name gets ommitted in the output array. Why is that?

def get_string_list(string_textfile):
    list = []
    file = open("names.txt", "r")
    for line in file:
       line = file.readline()[:-1]
       list.append(line.lower())

    return list
Pit R.
  • 11
  • 3
  • 1
    @dumbPy .... readlines() will be lines in a list ... read is a big string – Joran Beasley May 22 '20 at 01:07
  • Change 'line = file.readline()[:-1]' to 'line = line[:-1]'. Every second line is omitted because you are already iterating through the lines in the file via your for-loop. – Paul M. May 22 '20 at 01:08
  • im not entirely sure but i think when you iterate a file it strips the newline off for you – Joran Beasley May 22 '20 at 01:10
  • @PaulM. Thanks, that worked wonderfully! – Pit R. May 22 '20 at 01:11
  • 1
    Since you have blank lines you want to ignore (i.e. only want the names), check [easiest method to ignore blank lines](https://stackoverflow.com/questions/4842057/easiest-way-to-ignore-blank-lines-when-reading-a-file-in-python) (basically use strip function). – DarrylG May 22 '20 at 01:13
  • @PaulM. Could you post your reply as answer so I can mark it as solution? – Pit R. May 22 '20 at 14:51

2 Answers2

1

when you iterate the file

for line in file:
    # you read line just now it exists
    line = file.readline() 
    # uh oh you just read another line... you didnt do anything with the first one

dont mix iteration of a file with readline in general (in fact i think modern python versions will throw an error if you try to mix these two)

if all you want is a list of lines you can do any of the following

lines = list(file)
# or 
lines = file.readlines()

you can get only non_empty lines and strip newlines as follows

lines_stripped = list(filter(None,(l.strip() for l in file)))

not super pythonic but its nice and terse and pretty clear what its doing

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
0

modify for statements like following:

for line in file:
    list.append(line.strip().lower())
list = [name for name in list if name]

last line added to remove empty line.

정도유
  • 559
  • 4
  • 6