首先,我正在将文本文件读入字符串数组。然后我在每个元素加载到数组后删除换行符。这些步骤很好。最后,我想过滤掉字符串数组中不是文件名的任何元素(以“/”开头)。
我想知道我是否可以使用与剥离换行相同的语法来实现这一点,即“file_array = [word.strip()for file_array中的单词”“
代码摘录:
# read file into string array
with open(bom_filename, 'r') as my_file:
file_array = my_file.readlines()
# remove newline from strings
file_array = [word.strip() for word in file_array]
# filter out records that are not filenames
file_array = [if word[0]=="/" for word in file_array] <= could I do something like this?
虽然这种语法非常有用,但我对它并不熟悉!可以使用条件语句吗?
提前致谢...
答案 0 :(得分:4)
with open(bom_filename, 'r') as my_file:
file_array = [word.strip() for word in my_file if word.startswith("/")]
无需致电.readlines()