如果我有一个文本文件,在我得到我真正想要的东西之前有一堆随机文本,我如何将文件指针移到那里?在
例如,我的文本文件如下所示:
#foeijfoijeoijoijfoiej ijfoiejoi jfeoijfoifj i jfoei joi jo ijf eoij oie jojf
#feoijfoiejf ioj oij oi jo ij i joi jo ij oij #### oijroijf 3## # o
#foeijfoiej i jo i iojf 3 ## #io joi joij oi j## io joi joi j3# 3i ojoi joij
# The stuff I care about
(标签是实际文本文件的一部分)
如何将文件指针移动到我关心的内容行,然后如何让python告诉我行的编号,并从那里开始读取文件?在
我尝试过循环查找最后一个hashtag所在的行,然后从那里读取,但是我仍然需要去掉hashtag,并需要行号。在
在不知道垃圾数据的大小或扫描垃圾数据的情况下,您无法直接查找它。但是,将文件包装在^{} 中以丢弃行并不难,直到您看到“良好”的数据,之后它将遍历所有剩余的行:
如果您确实需要适当定位文件描述符,而不仅仅是行,那么这个变量应该可以工作:
^{pr2}$如果您真的需要(而不是仅仅需要偏移量),您可以调整它以获得实际的行号。但是它的可读性稍差,因此如果需要,通过
enumerate
显式迭代可能更有意义(留作练习)。让Python为您工作的方法是:尝试使用readlines函数。这将返回一个包含每一行的列表。您可以使用
for
循环来分析每一行,搜索所需内容,然后通过列表中的索引获得该行的编号。例如:要去掉井号,只需使用replace函数。例如
new_line = line.replace('#','')
相关问题 更多 >
编程相关推荐