Friday, 13 September 2013

How to get Python File Output to CSV

How to get Python File Output to CSV

I have the following script, and I am trying to move the output of the
script to a CSV file. The problem is I do not know where to start. I am
thinking of using import CSV, but I am not sure where to go from there.
This is Python 3 and I am not finding a lot of clear explanations and some
are really advanced, which I am not. This is my program that I currently
have. I tried to throw in a return at the end of the loop, but I get a out
of function error. I know I should use a break to end a loop, but then
where do I go from there?
String that is used
s = """10.0.1.2 - - [19/Apr/2010:06:36:15 -0700] "GET /feed/ HTTP/1.1" 200
16605 "-" "Apple-PubSub/65.12.1" C4nE4goAAQ4AAEP1Dh8AAAAA 3822005"""
Variables that are going to be used
inquote = False # You have to declare the state of inquote in order for
the iteration to properly switch. Changing this to True alters the results
newstring = '' # You are declaring newstring is equal to whitespace
Start of the for nested loop
for i in range(0,len(s)): # this is the start of the for loop. In this
portion you are going to look at each character one by one if s[i] == '"':
# Found a quote see if its the beg or end if inquote == False: # This is
the beginning state of s inquote = True
else:
inquote = False #This is changing the state to False. In
changing the state to False then it stops looking at the
quotations.
if s[i] == " ": # This section looks at s and the string to determine
quotation marks. If not in quotation marks then a comma is added to
whitespace. In turn this is iterated over and over
if not inquote:
newstring += ','
else:
newstring += s[i]
else:
newstring += s[i]
brack1=newstring.replace('[','')
brack2=brack1.replace(']','')

No comments:

Post a Comment