Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用于从txt理解列表的python空列表输出_Python_List Comprehension_Readlines_Startswith - Fatal编程技术网

用于从txt理解列表的python空列表输出

用于从txt理解列表的python空列表输出,python,list-comprehension,readlines,startswith,Python,List Comprehension,Readlines,Startswith,尝试读取txt文件并过滤不相关的行。 有些行是随机字符串,有些带有“#”哈希标记字符 base_txt = open(path, 'rU') txt = base_txt.readlines() txt = [x for x in base_txt if x.startswith('#')] print txt print len(txt) 输出为空列表。如果我在列表理解之前打印txt,那么它会打印出文件中的所有字符串 是否有语法错误?您的代码没有问题,只是循环使用了错误的变量

尝试读取txt文件并过滤不相关的行。 有些行是随机字符串,有些带有“#”哈希标记字符

base_txt = open(path, 'rU')
  txt = base_txt.readlines()
  txt = [x for x in base_txt if x.startswith('#')]
  print txt
  print len(txt)
输出为空列表。如果我在列表理解之前打印txt,那么它会打印出文件中的所有字符串


是否有语法错误?

您的代码没有问题,只是循环使用了错误的变量。应该是

txt = [x for x in txt if x.startswith('#')]
而不是

txt = [x for x in base_txt if x.startswith('#')]

你能在你的问题中粘贴5-10行文本文件吗?你在循环错误的变量。应该是
txt=[x代表x在txt中…]
代表x在base\u txt中
->
代表x在txt中
。第二次读取行时,文件指针位于末尾。