2

I have the following code which writes a data output to a csv file. I want to add a date variable at the end of each row using the yesterday.strftime variable that i am using in creating the filename. For example:

Thanks!

my current output is like:

columnA

1

2

and I want to add the following column:

Date

2/5/2016

2/5/2016

. . .

CODE::

filepath = 'C:\\test\\'   
filename = yesterday.strftime('%Y-%m-%d') + '_' + 'test.csv'

f = open( filename, 'wt')
writer = csv.writer(f, lineterminator='\n')
header = [h['name'][3:] for h in results.get('columnHeaders')] 
writer.writerow(header)
print(''.join('%30s' % h for h in header))

# Write data table.
if results.get('rows', []):
  for row in results.get('rows'):
    writer.writerow(row)
    print(''.join('%30s' % r for r in row))

else:
  print ('No Rows Found')

f.close()
2
  • Where does results come from? You might have to look there Commented Feb 5, 2016 at 19:00
  • FYI, you can replace if results.get('rows', []):, for row in results.get('rows'): with just if results.get('rows'):, for row in results['rows']:; the first usage doesn't use the default for anything but a boolean test (so the default default of None is fine), and the second already knows the key exists, so no need to use .get at all. Commented Feb 5, 2016 at 19:39

1 Answer 1

1
In [26]: import pandas as pd

In [27]: import datetime

In [28]: a = pd.read_csv('a.csv')

In [29]: a
Out[29]: 
columnA
0        1
1        2

In [30]: a['Date'] = [datetime.date.today()]*len(a)

In [31]: a
Out[31]: 
columnA        Date
0        1  2016-02-05
1        2  2016-02-05

In [32]: a.to_csv('adate.csv')

Generally: https://www.airpair.com/python/posts/top-mistakes-python-big-data-analytics

Sign up to request clarification or add additional context in comments.

1 Comment

First off thanks for posting. I ran the code, but it's adding an index field of some sort to the beginning of my file. Is there a way for me to omit that or give it a name? currently it's just blank.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.