您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python:从文件中选择随机行,然后删除该行

Python:从文件中选择随机行,然后删除该行

我有一个文件“ TestingDeleteLines.txt”,大约300行文本。现在,我正在尝试使其从该文件中打印10条随机行,然后删除这些行。

    #!/usr/bin/env python
    import random

    k = 10
    filename = 'TestingDeleteLines.txt'
    with open(filename) as file:
        lines = file.read().splitlines()

    if len(lines) > k:
        random_lines = random.sample(lines, k)
        print("\n".join(random_lines)) # print random lines

        with open(filename, 'w') as output_file:
            output_file.writelines(line + "\n"
                                   for line in lines if line not in random_lines)
    elif lines: # file is too small
        print("\n".join(lines)) # print all lines
        with open(filename, 'wb', 0): # empty the file
            pass
python 2022/1/1 18:13:40 有733人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶