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 9204781
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T23:47:31+00:00 2026-06-17T23:47:31+00:00

To set the context I have a directory with 200-300 files, each file ranges

  • 0

To set the context I have a directory with 200-300 files, each file ranges in size (# of lines). I pase the files and export them to a csv file. I think the last time I ran it the csv file had over 340,000 rows. On top of that the first 8 files are constantly being written to so I lose data while parsing sometimes.

Now, each file is set up like this:

DateTime Message Action ActionDetails

I have code in place to take go through all the files, parse them and then output to a csv file:

for infile in listing:
    _path2 = _path + infile
    f = open(_path2, 'r')
    labels = ['date', 'message', 'action', 'details']
    reader = csv.DictReader(f, labels, delimiter=' ', restkey='rest')

    for line in reader:
        if line.get('rest'):
            line['details'] += ' %s' % (' '.join(line['rest']))
        out_file.write(','.join([infile,line['date'], line['message'], line['action'], line['details']]) + '\n')

    f.close()
out_file.close()

I was wondering what the “best” way to go about copying the first 8 files so I don’t lose data while parsing would be. By best I mean take the least amount of time as the total time to run the python script at the moment is about 35-45 seconds.

  • 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-17T23:47:32+00:00Added an answer on June 17, 2026 at 11:47 pm

    I got a little bored. Try this on for size. I didn’t actually have a chance to check if it was parsing and writting correctly but other than that I believe it should run given some info. This problem is a good opportunity to use queueing. Let me know how fast it runs!

    from threading import Thread
    import Queue
    import os
    import time
    import sys
    
    # declare some global items
    # queue that an author thread can write line items to a csv
    write_q = Queue.Queue()
    
    # queue filled with files to parse 
    read_q = Queue.Queue()
    
    # queue filled with files that have size change during read. Can
    # preload this queue to optimize however program should handle any
    # file that changes during operation
    moving_q = Queue.Queue()
    
    # given csv labels
    labels = ['date', 'message', 'action', 'details']
    
    # global for writer thread so it knows when to close
    files_to_parse = True
    
    # parsing function for any number of threads
    def file_parser():    
        # Each parser thread will run until the read_q is empty
        while True:
            moving = False
            # Test for a file from the read queue or moving queue 
            try:
                if not moving_q.empty():
                    try:
                        f_path = moving_q.get(False)
                        moving = True
                    # if the moving queue is empty after trying to read
                    # might have been snatched by different thread. Ignore error
                    except Queue.Empty:
                        pass
                else:
                    # No items left in moving queue so grab non moving file
                    f_path = read_q.get(False)
            # all files have been dealt with
            except Queue.Empty:
                print "Done Parsing"
                sys.exit()
    
            # Following will parse a file and test that the file is not being
            # modified during the read
            with open(f_path, 'r') as f:
                # csv reader setup
                reader = csv.DictReader(f, labels, delimiter=' ', restkey='rest')
    
                # initillized file size (when we started reading)
                pre = os.path.getsize(f_path)
    
                # store output items in a list so if file is updated during read
                # we can just ignore those items and read file later
                line_items = []
    
                # parse the file line by line
                for line in reader:
                    # Check that file hasn't been updated
                    post = os.path.getsize(f_path)
                    if pre != post:
                        # if file has changed put the file back on the queue and clear the output lines
                        moving_q.put(f_path)
                        line_items = None
                        break
                    # parse the line and add it to output list
                    else:
                        if line.get('rest'):
                            line['details'] += ' %s' % (' '.join(line['rest']))
                            line_items.append(','.join([infile,line['date'], line['message'], line['action'], line['details']]) + '\n')
    
                # don't want to do reading and writing in same thread. Push
                # all line items onto the write thread for the author to deal with    
                if line_items and moving:
                    write_q.put(line_items)
                    moving_q.task_done()
                elif line_items and not moving:
                    write_q.put(line_items)
                    read_q.task_done()
    
    # author thread that will write items to a file as other threads complete
    # tasks. Should help speed up IO bound processing
    def file_author(out_file):
        with open(out_file,'w') as f:
            # parse files until all the parser threads are running
            while files_to_parse or not read_q.empty():
                # only one writer thread so write as items are put into thread
                if not read_q.empty():
                    line_items = write_q.get(False)
                    for line_item in line_items:
                        f.write(line_item)
                    write_q.task_done()
                # sleep in the downtime so we dont overload PC
                else:
                    time.sleep(.1)
        print "Done writting"
    
    
    if __name__ == "__main__":
        # list of file names as you had before
        listing = []
        outfile = "MyNewCSVfile.csv"
    
        # You can optimize parsing by adding known "moving files" directly
        # to the moving_queue, however program should handle either way
        for infile in listing:
            _path2 = _path + infile
            write_q.put(_path2)
    
        # make a writer thread
        t = Thread(target = file_author, args = (outfile,))
        t.daemon = True
        t.start()
    
        # make some parse threads
        for i in range(10):
            t = Thread(target = file_parser)
            t.daemon = True
            t.start()
    
        # wait for parser threads to finish work
        read_q.join()
        moving_q.join()
    
        # close author
        files_to_parse = False
        time.sleep(.1)
        print "Complete"
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Context We have a SharePoint site set up on a Windows Server 2008 VM
I have a list view filled with data. I set up a context menu
The context: i have a project, that contains configs/ directory, which contains (surprise-surprise!) a
I have a some application specific file which are stored in a directory in
I have ArrayAdapter, where I set array of files: adapter = new ArrayAdapter<Item>(this, R.layout.file_manager,
Apache's Order/Allow/Deny directives are permitted within a <Directory> context. What happens when a set
I currently have my 'WebSocketMain.swf' file sitting in the same directory as 'socket.io.min.js' but
I have file channel adapter which need to listen to a directory in specfied
I have some content set to be in 3 columns, but as it wraps
In my servlet I have the following code: response.setContentType(application/json);//set json content type PrintWriter out

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.