简体   繁体   中英

How do I make a list from a textfile in Python?

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM