I am a newbie in Python, and I only have been programming in the language for the third day. I convert from Matlab because I am graduating from university and I just cannot afford the heavy cost of the software.
I am trying to add several filenames to a list, which fails. The following is my code:
import os
dirname = r"D:\MyFiles"
temp = os.listdir(dirname)
fl = []
for fn in temp:
if fn.startswith('L0116'):
fl = fl.append(fn)
What I don’t understand is, the variable fl when initiated with [] returns as the list type, but then I fail to append the list with the above loop. I recheck my code using interactive prompt and I found out that the type changes to str and fails to append more.
I am stuck at this and I tried to google for about an hour without any clear clue to how I should do this.
Is there a better way? Or which part did I do it wrong?
Thank you so much for your help!
The
append()method mutates the list in place. You should just appendfnlike this:don’t try to assign the result of
fl.append(fn)(which isNone, by the way)Also, don’t use
r"foo"strings for filenames. They are designed for use with regular expressions and using them for filenames or other kinds of strings will bite you. For example, you cannot end such a string with a backslash.