社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
私信  •  关注

sandes

sandes 最近创建的主题
sandes 最近回复了
5 年前
回复了 sandes 创建的主题 » 使用Python从文本文件中删除特定数量的行

根据基尼的评论

with open("your_file.txt", "r") as f:
    lines = f.readlines()
    new_lines = []
    idx_lines_wanted = [2,3,4]
    for i, line in enumerate(lines):
        if i > 4:
            break
        if i in idx_lines_wanted:
             new_lines.append(line)

with open("your_file.txt", "w") as f:
    for line in new_lines:
        f.write(line)

关于这个: 如果文件顶部有1-100行要删除

idx_lines_wanted = [x for x in range(0,101)]

if i > len(idx_lines_wanted) -1: