简体   繁体   中英

Python: if len(list) giving different results in different circumstances?

I am trying to write a music program in Python that takes some music written by the user in a text file and turns it into a midi. I'm not particularly experienced with python at this stage so I'm not sure what the reason behind this issue is. I am trying to write the source file parser for the program and part of this process is to create a list containing all the lines of the text file and breaking each line down into its own list to make them easier to work with. I'm successfully able to do that, but there is a problem.

I want the code to ignore lines that are only whitespace (So the user can make their file at least kind of readable without having all the lines thrown together one on top of the other), but I can't seem to figure out how to do that. I tried doing this

with open(path, "r") as infile:
    for row in infile:
        if len(row):
            srclines.append(row.split())

And this does work as far as creating the list of lines and separating each word goes, BUT it still appends the empty lines that are only whitespace... I confirmed this by doing this

for entry in srclines:
    print entry

Which gives, for example

['This', 'is']
[]
['A', 'test']

With the original text being

This is

A test

But strangely, if during the printing stage I do another len() check then the empty lines are actually ignored like I want, and it looks like this

['This', 'is']
['A', 'test']

What is the cause of this? Does this mean I can only go over the list and remove empty entries after I generate It? Or am I just doing the line import code wrong? I am using python 3.6 to test this code with by the way

row contains a newline, so it's not empty. But row.split() doesn't find any non-whitespace characters, so it returns an empty list.

Use

if len(row.strip()):

to ignore the newline (and any other leading/trailing spaces).

Or more simply:

if row.strip():

since an empty string is falsy.

Try creating a list comprehension :

with open('d.txt', "r") as infile:
    print([i.strip().split() for i in infile if i.strip()])

Output:

[['This', 'is'], ['A', 'test']]

testdoc.txt has lot of empty lines; but in output they are out;

src = 'testdoc.txt'
with open(src, 'r') as f:
    for r in f:
        if len(r) > 1:
            print(r.strip())

and now you can obviously put this all in list or in list line by line instead of print whatever fits your further logic

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