Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8433377
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T06:22:11+00:00 2026-06-10T06:22:11+00:00

I have many tasks in .txt files in multiple sub folders. I am trying

  • 0

I have many tasks in .txt files in multiple sub folders. I am trying to pick up a total 10 tasks randomly from these folders, their contained files and finally a text line within a file. The selected line should be deleted or marked so it will be not picked in the next execution. This may be too broad a question but I’d appreciate any input or direction.

Here’s the code I have so far:

#!/usr/bin/python  
import random   
with open('C:\\Tasks\\file.txt') as f:  
    lines = random.sample(f.readlines(),10)    
print(lines)
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T06:22:13+00:00Added an answer on June 10, 2026 at 6:22 am

    To get a proper random distribution across all these files, you’d need to view them as one big set of lines and pick 10 at random. In other words, you’ll have to read all these files at least once to at least figure out how many lines you have.

    You do not need to hold all the lines in memory however. You’d have to do this in two phases: index your files to count the number of lines in each, then pick 10 random lines to be read from these files.

    First indexing:

    import os
    
    root_path = r'C:\Tasks\\'
    total_lines = 0
    file_indices = dict()
    
    # Based on https://stackoverflow.com/q/845058, bufcount function
    def linecount(filename, buf_size=1024*1024):
        with open(filename) as f:
            return sum(buf.count('\n') for buf in iter(lambda: f.read(buf_size), ''))
    
    for dirpath, dirnames, filenames in os.walk(root_path):
        for filename in filenames:
             if not filename.endswith('.txt'):
                 continue
             path = os.path.join(dirpath, filename)
             file_indices[total_lines] = path
             total_lines += linecount(path)
    
    offsets = list(file_indices.keys())
    offsets.sort()
    

    Now we have a mapping of offsets, pointing to filenames, and a total line count. Now we pick ten random indices, and read these from your files:

    import random
    import bisect
    
    tasks = list(range(total_lines))
    task_indices = random.sample(tasks, 10)
    
    for index in task_indices:
         # find the closest file index
         file_index = offsets[bisect.bisect(offsets, index) - 1]
         path = file_indices[file_index]
         curr_line = file_index
         with open(path) as f:
             while curr_line <= index:
                 task = f.readline()
                 curr_line += 1
         print(task)
         tasks.remove(index)
    

    Note that you only need the indexing once; you can store the result somewhere and only update it when your files update.

    Also note that your tasks are now ‘stored’ in the tasks list; these are indices to lines in your files, and I remove the index from that variable when printing the task selected. Next time you run the random.sample() choices, the tasks previously picked will no longer be available for picking the next time. This structure will need updating if your files ever do change, as the indexes have to be re-calculated. The file_indices will help you with that task, but that is outside the scope of this answer. 🙂

    If you need only one 10-item sample, use Blckknght’s solution instead, as it only will go through the files once, while mine require 10 extra file openings. If you need multiple samples, this solution only requires 10 extra file openings every time you need your sample, it won’t scan through all the files again. If you have fewer than 10 files, still use Blckknght’s answer. 🙂

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am using SVN for development tasks, but still have many files managed with
I have a C# Windows application that does many tasks. some of these tasks
We have many C# console apps that run on scheduled tasks. All of these
I have a model relationship where today has many tasks I'm trying to retrieve
Projects have many tasks and a task has a custom RESTful action called 'approve'.
I have a service responsible for many tasks, one of which is to launch
I have many different NSArray 's stored in .dat files, in the Documents folder
I have many many files in a folder, and I want to process them
I have many directories with files in them. I want to create a comma
We have many projects with several files inside each. Files can be checked in

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.