Python的:选择随机行的文件,然后删除该行 [英] Python: Choose random line from file, then delete that line

查看:262
本文介绍了Python的:选择随机行的文件,然后删除该行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的Python(在我经历了codeAcademy过程中学会了它),可以用搞清楚了这一点使用一些帮助。

我有一个文件,TestingDeleteLines.txt,这是大约300行文字。现在,我想要得到它从该文件打印我的10个随机行,然后删除这些行。

所以,如果我的文件有10行:

胡萝卜

香蕉

草莓

Canteloupe

蓝莓

零食

苹果公司

木瓜

西瓜

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

问题是,当Python的读取文件时,它读取该文件,一旦它到达结束,也不会回去删除线。我现在的想法是,我可以写的行到一个列表,然后重新打开该文件,匹配列表的文本文件,如果找到一个匹配,删除线。

我现在的问题是双重的:

  1. 在它复制的随机元素。如果选取一条线,我需要它不会再挑同一条线上。但是,使用random.sample似乎并没有工作,因为我需要这些线路中分离出来,当我后来用每行追加到URL。
  2. 我不觉得我的逻辑(写入基于阵列>查找文本文件 - >删除匹配)是最为理想的逻辑。有没有更好的方式来写这个?

     导入网页浏览器
    进口随机
    
    URL =http://www.google.com
    webbrowser.open_new_tab(网址+ MYLINE)最后,我需要一个基本URL +我的10个随机行开在每一个新的选项卡
    
    高清ShowMeTheRandoms():
        X = 1
        DeleteList = []
        线路=打开('TestingDeleteLines.txt')。read()方法。splitlines()
    对于x范围内(0,10):
        MYLINE = random.choice(行)
        打印(MYLINE)调试,后来去掉
        DeleteList.append(MYLINE)
        X = X + 1个
        打印DeleteList调试,后来去掉
    ShowMeTheRandoms()
     

解决方案

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

 开放(/路径/到/的Source.txt)作为源文件,打开(/路径/到/ TEMP.TXT,W)为DEST:
    在SRC线:
        如果should_we_keep_this_line(线):
            dest.write(线)
os.rename(/路径/到/ TEMP.TXT,/path/to/source.txt)
 

I'm new to Python (in that I learned it through a CodeAcademy course) and could use some help with figuring this out.

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.

So if my file has 10 lines:

Carrot

Banana

Strawberry

Canteloupe

Blueberry

Snacks

Apple

Raspberry

Papaya

Watermelon

I need it to randomly pick out from those lines, tell me it's randomly picked blueberry, carrot, watermelon, and banana, and then delete those lines.

The issue is, when Python reads a file, it reads that file and once it gets to the end, it won't go back and delete the lines. My current thinking was that I could write the lines to a list, then reopen the file, match the list to the text file, and if it finds a match, delete the lines.

My current problem is twofold:

  1. It's duplicating the random elements. If it picks a line, I need it to not pick that same line again. However, using random.sample doesn't seem to work, as I need those lines separated out when I later use each line to append to a URL.
  2. I don't feel like my logic (write to array->find matches in text file->delete) is the most ideal logic. Is there a better way to write this?

    import webbrowser
    import random
    
    """url= 'http://www.google.com'
    webbrowser.open_new_tab(url+myline)""" Eventually, I need a base URL + my 10 random lines opening in each new tab
    
    def ShowMeTheRandoms():
        x=1
        DeleteList= []
        lines=open('TestingDeleteLines.txt').read().splitlines()
    for x in range(0,10):
        myline=random.choice(lines)
        print(myline) """debugging, remove later"""
        DeleteList.append(myline)
        x=x+1
        print DeleteList """debugging, remove later"""
    ShowMeTheRandoms()
    

解决方案

Point is: you dont "delete" from a file, but rewrite the whole file (or another one) with new content. The canonical way is to read the original file line by line, write back the lines you want to keep to a temporary file, then replace the old file with the new one.

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")

这篇关于Python的:选择随机行的文件,然后删除该行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆