python - 如果我以附加模式打开文本文件,我可以找出我所在的行号吗?

标签 python io

我想做的是:

with open(textfile, 'at') as f:
    f.write(f'{current_line_number}: ' + "Some text" + '\n')

最佳答案

您可以使用'r+'(读写模式)打开文件,然后您可以使用readlines()获取行列表并计算列表有多少行len(),然后只需在结果中添加+1:len(f.readlines()) + 1,您就可以得到文件有多少行。像这样的事情:

with open(textfile, 'r+') as f:
    current_line_number = len(f.readlines()) + 1
    f.write(f'{current_line_number}: ' + "Some text" + '\n')

关于python - 如果我以附加模式打开文本文件,我可以找出我所在的行号吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75664281/

相关文章:

windows - PerlIO::encoding 的意外行为

clojure - 维护多个打开的文件以进行写入 (Clojure)

c++ - ios::app 和用于输入的 fstream 之间的交互

windows - 我应该将临时文件写入临时目录吗?或者将临时文件写入最终目录?

python - Pandas .title() 当字符串有一个 's

python - Tweepy 和 flask : failed to get request token

python - Django 中 MySQL 配置不正确

python - 为什么在 Django 中使用 callproc() 时出现 PROCEDURE 不存在?

python - Markdown 链接到 Sphinx 中的 reStructuredText anchor

postgresql - Cassandra 如何处理磁盘 IO