简体   繁体   English

对不复杂的列表进行不必要的修改

[英]Unwanted modification of not intricated lists

here is the code:这是代码:

with open('units.txt', 'r') as f:
   print(f.readlines())
   e = [elt.split(" ")[0] for elt in f.readlines()]
   print(f.readlines())

and here is the result:结果如下:

['INPUT 0 2 #ffffff # # #\n', 'OUTPUT 2 0 #ffffff # # #\n', 'NOT 1 1 #ff0000 # # #\n', 'AND 2 1 #8888ee # # #\n', 'NAND 2 1 #ff00ff INPUT_OUTPUT_AND_NOT_ #3,0,_#0,0,_0,1,_#2,0,_# 0_3_2_1_']       
[] 

what am i missing?我错过了什么?

You've already called readlines() on an open file.您已经在打开的文件上调用了readlines() You need to reset the file pointer using file.seek(0) before calling it again.您需要在再次调用之前使用file.seek(0)重置文件指针。

You can't keep calling readlines on the file, because the first consumes the entire file then the rest doesn't read anything.您不能继续在文件上调用readlines ,因为第一个会消耗整个文件,然后 rest 不会读取任何内容。 Store it to a variable:将其存储到变量中:

with open('units.txt', 'r') as f:
   lines = f.readlines()
   print(lines)
   e = [elt.split(" ")[0] for elt in lines]
   print(lines)

Alternatively, call f.seek(0) between calls to reset the file pointer, but storing to a variable is far cleaner.或者,在调用之间调用f.seek(0)以重置文件指针,但存储到变量要干净得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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