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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 29, 20262026-05-29T04:47:24+00:00 2026-05-29T04:47:24+00:00

I’m fairly rusty with my python and wanted to know if there was a

  • 0

I’m fairly rusty with my python and wanted to know if there was a better way or more efficient way of writing this script.

The scripts purpose it to take a txt log and replace ‘ ‘ with replace with ‘,’ to create a .csv.. Makes the logs a little easier to read.

Any suggestions or advice would be appreciated.
Thanks.

import sys
import os
import datetime

t = datetime.datetime.now() ## time set to UTC zone
ts = t.strftime("%Y_%m_%d_ %H_%M_%S") # Date format


if len(sys.argv) != 2: # if CLi does not equal to 2 commands print
print ("usage:progammename.py logname.ext")

sys.exit(1)

logSys = sys.argv[1] 
newLogSys = sys.argv[1] + "_" + ts +".csv"

log = open(logSys,"r")
nL = file(newLogSys  ,"w") 


# Read from file log and write to nLog file
for lineI in log.readlines():
    rec=lineI.rstrip()
    if rec.startswith("#"):
        lineI=rec.replace(':',',').strip() 
        nL.write(lineI + "\n")
    else:
        lineO=rec.replace(' ',',').strip() #
        nL.write(lineO + "\n") 

## closes both open files; End script
nL.close()
log.close()

=====Sample log========
#Date: 2008-04-18 15:41:16
#Fields: date time time-taken c-ip cs-username cs-auth-group x-exception-id sc-filter-result cs-categories cs(Referer) sc-status s-action cs-method rs(Content-Type) cs-uri-scheme cs-host cs-uri-port cs-uri-path cs-uri-query cs-uri-extension cs(User-Agent) s-ip sc-bytes cs-bytes x-virus-id
2012-02-02 16:19:01 14 xxx.xxx.xxx.xxx user domain\group dns_unresolved_hostname DENIED "Games" -  404 TCP_ERR_MISS POST - http updaterservice.wildtangent.com 80 /appupdate/appcheckin.wss - wss "Mozilla/4.0 (compatible; MSIE 8.0; Win32)" xxx.xxx.xxx.xxx 824 697 -
  • 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-05-29T04:47:26+00:00Added an answer on May 29, 2026 at 4:47 am

    I would shorten your code to:

    import sys
    import os
    from time import strftime
    
    if len(sys.argv) != 2: # if CLi does not equal to 2 commands print
        print ("usage:progammename.py logname.ext")
        sys.exit(1)
    
    logSys    = sys.argv[1]
    newLogSys = "%s_%s.csv" % (logSys,strftime("%Y_%m_%d_ %H_%M_%S"))
    
    with open(logSys,'rb') as log, open(newLogSys,'wb') as nL:
        nL.writelines(lineI.replace(':' if lineI[0]=='#' else ' ', ',')
                      for lineI in log)
    

    edit

    I still don’t understand what you mean by the addition of another line, that is to say ‘\n’, to lines other than those that begin with ‘#’

    I ran the following code with your sample and I didn’t observe something looking like what you describe. Sorry, but I can’t propose any solution for a problem I don’t perceive .

    from time import strftime
    import re
    
    ss = ('--||  ||:|||:||--||| \r\n'
          '#10 23:30 abcdef : \r\n'
          '802 12:25 xyz  :  \r\n'
          '\r\n'
          '#:35 11:18+14:39 sunny vale : sunny sea\r\n'
          '  651454451 drh:hdb 54:1\r\n'
          '    \r\n'
          ': 541514 oi:npvert654165:8\r\n'
          '#5415:v541564zervt\r\n'
          '#     ::    \r\n'
          '#::: :::\r\n'
          ' E\r\n')
    
    regx = re.compile('(\r?\n(?!$))|(\r?\n$)')
    
    def smartdispl(com,smth,regx = regx):
        print '\n%s\n%s\n%s' %\
              ('{0:{fill}{align}70}'.format(' %s ' % com,fill='=',align='^'),
               '\n'.join(repr(el) for el in smth.splitlines(1)),
               '{0:{fill}{align}70}'.format('',fill='=',align='^'))
    
    logSys = 'poiu.txt'
    
    with open(logSys,'wb') as f:
        f.write(ss)
    
    with open(logSys,'rb') as f:
        smartdispl('content of the file '+logSys,f.read())
    
    newLogSys = "%s_%s.csv" % (logSys,strftime("%Y_%m_%d_ %H_%M_%S"))
    
    with open(logSys,'rb') as log, open(newLogSys,'wb') as nL:
        nL.writelines(lineI.replace(':' if lineI[0]=='#' else ' ', ',')
                      for lineI in log)
    
    with open(newLogSys,'rb') as f:
        smartdispl('content of the file '+newLogSys,f.read())
    

    result

    ==================== content of the file poiu.txt ====================
    '--||  ||:|||:||--||| \r\n'
    '#10 23:30 abcdef : \r\n'
    '802 12:25 xyz  :  \r\n'
    '\r\n'
    '#:35 11:18+14:39 sunny vale : sunny sea\r\n'
    '  651454451 drh:hdb 54:1\r\n'
    '    \r\n'
    ': 541514 oi:npvert654165:8\r\n'
    '#5415:v541564zervt\r\n'
    '#     ::    \r\n'
    '#::: :::\r\n'
    ' E\r\n'
    ======================================================================
    
    ======= content of the file poiu.txt_2012_02_07_ 00_48_55.csv ========
    '--||,,||:|||:||--|||,\r\n'
    '#10 23,30 abcdef , \r\n'
    '802,12:25,xyz,,:,,\r\n'
    '\r\n'
    '#,35 11,18+14,39 sunny vale , sunny sea\r\n'
    ',,651454451,drh:hdb,54:1\r\n'
    ',,,,\r\n'
    ':,541514,oi:npvert654165:8\r\n'
    '#5415,v541564zervt\r\n'
    '#     ,,    \r\n'
    '#,,, ,,,\r\n'
    ',E\r\n'
    ======================================================================
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
Does anyone know how can I replace this 2 symbol below from the string
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
link Im having trouble converting the html entites into html characters, (&# 8217;) i
For some reason, after submitting a string like this Jack’s Spindle from a text
this is what i have right now Drawing an RSS feed into the php,
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
I am writing an app with both english and french support. The app requests
I have some data like this: 1 2 3 4 5 9 2 6
That's pretty much it. I'm using Nokogiri to scrape a web page what has

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.