在文件读取内容时,有可能发现open一个文件,再读取到list或者dict中只能读取一次,再定义一个变量进行文件内容的赋值时会取出空值。

with open('./goods.txt','r') as fg:
result = list(line.strip().split(':') for line in fg if line)
result2 = dict(line.strip().split(':') for line in fg if line) #取出为空值

 

原因:这是由于读取文件时,指针从文件开头移到文件结尾,再定义的变量取值时,会从文件结尾开始读取。

解决方法:结合seek、tell方法

with open('./goods.txt','r') as fg:
result = list(line.strip().split(':') for line in fg if line)
fg.seek(0)
result2 = dict(line.strip().split(':') for line in fg if line)

tell方法--取出字符的位置

 

 Python3.x使用with打开文件,可同时打开多个文件:

with open('music','r') as f1,\
open('music.txt','w') as f2:

相关文章:

  • 2021-12-01
  • 2021-09-16
  • 2022-12-23
  • 2022-12-23
  • 2021-07-22
  • 2022-01-12
  • 2021-08-15
  • 2022-02-12
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-07-12
  • 2023-02-17
  • 2021-04-16
  • 2022-12-23
  • 2021-09-28
相关资源
相似解决方案