如果我没有恰当地问这个问题,我道歉。这有点令人困惑。举个直观的例子如果我有这个txt文件:
| $100 on the first line
| $654 on the second line
| $123 on the third line
| $111 on the fourth line
我怎样才能找到最后一次使用$
来打印111
的时间?
您可以使用str.rfind()
来获取字符串的最后一个实例(反向先查找),然后使用它来索引字符串。
import io
file = "| $100 on the first linen| $654 on the second linen| $123 on the third linen| $111 on the fourth line"
txt = io.StringIO(file).getvalue()
idx = txt.rfind('$')
#txt[idx+1:idx+4]
txt[idx+1:].split()[0] #takes the complete first token instead of 3 characters
'111'
根据您的需要,bash可能更有效。从shell命令行:
$ grep "$" file.txt | cut -d "$" -f2 | cut -d " " -f1 | tail -1
输出:111
对于小文件,请参见:如何按倒序读取文件?
对于需要考虑磁盘的大文件,可以尝试使用seek()来结束文件并回读(以块为单位)