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

2024-05-13 23:45:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python的新手(因为我是通过codeaccademy课程学习的),所以我需要一些帮助来解决这个问题。在

我有一份档案,'测试删除线.txt'大约有300行文字。现在,我试着让它从文件中随机打印10行,然后删除这些行。在

如果我的文件有10行:

Carrot
Banana
Strawberry
Canteloupe
Blueberry
Snacks
Apple
Raspberry
Papaya
Watermelon

我需要它从这些行中随机挑选出来,告诉我是随机挑选的蓝莓、胡萝卜、西瓜和香蕉,然后删除这些行。在

问题是,当Python读取一个文件时,它会读取该文件,一旦它到达末尾,它就不会返回并删除这些行。我目前的想法是,我可以将行写入一个列表,然后重新打开文件,将列表与文本文件匹配,如果找到匹配项,则删除这些行。在

我目前的问题有两个:

  1. 它在复制随机元素。如果它选了一条线,我需要它不要再选同一条线。但是,使用random.sample似乎不起作用,因为我需要在以后使用每一行来附加到URL时将这些行分开。在
  2. 我觉得我的逻辑(write to array->;find matches in text file->delete)不是最理想的逻辑。有没有更好的方法来写这个?在

    ^{2美元

Tags: 文件txt列表档案逻辑课程banana文字
3条回答

I have a file, 'TestingDeleteLines.txt', that's about 300 lines of text. Right now, I'm trying to get it to print me 10 random lines from that file, then delete those lines.

#!/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

如果需要的话,O(n**2)算法是can be improved(对于像您的输入这样的小文件,您不需要它)

怎么办列表.pop-它将一步到位,并更新列表。在

lines = readlines()
deleted = []

indices_to_delete = random.sample(xrange(len(lines)), 10)

# sort to delete biggest index first 
indices_to_delete.sort(reverse=True)

for i in indices_to_delete:
    # lines.pop(i) delete item at index i and return the item
    # do you need it or its index in the original file than
    deleted.append((i, lines.pop(i)))

# write the updated *lines* back to the file or new file ?!
# and you have everything in deleted if you need it again

重点是:你不能从一个文件中“删除”,而是用新的内容重写整个文件(或另一个文件)。规范的方法是逐行读取原始文件,将要保留的行写回临时文件,然后用新文件替换旧文件。在

with open("/path/to/source.txt") as src, open("/path/to/temp.txt", "w") as dest:
    for line in src:
        if should_we_keep_this_line(line):
            dest.write(line)
os.rename("/path/to/temp.txt", "/path/to/source.txt")

相关问题 更多 >