Showing posts with label python_csv. Show all posts
Showing posts with label python_csv. Show all posts

Feb 12, 2019

Python csv write

from users.models import *
import sys

up = UserProfile.objects.all()
print up.count()

header = "Name, User Type, Email, Phone, City, Country, TimeZone, Created Date\n"

fname = "/tmp/user_data.csv"
with open(fname, 'w') as FW:
   FW.write(header)
   for each in up:
     try:
        name = each.name
        name = name.encode('utf-8').strip()
        dts = each.created_date
        dts = dts.strftime("%d %b %Y") #dts.strftime("%b %d %Y %I:%M %p")
        str1 = "%s,%s,%s,%s,%s,%s,%s,%s\n" % (str(name), str(each.usertype), str(each.email_id), str(each.phone), str(each.city), str(each.country), str(each.timezone), str(dts))
        #print str1
        FW.write(str1)
     except Exception, e:
        print '---- Error: ' + str(e)

print fname


Output:
Name, User Type, Email, Phone, City, Country, TimeZone, Created Date
User2,Student,user2@abc.com,None,Bangalore,IN,Asia/Kolkata,16 Mar 2018
User3,Student,user3@gmail.com,None,Pune,IN,Asia/Kolkata,28 Mar 2018
....


Jan 16, 2019

Python csv content to dictionary

import csv

file_name = 'student.csv'
input_file_handle = csv.DictReader(open(file_name, 'rb'))
for row in input_file_handle:
     print row  #This will print row as dictionary
     print row['id']
     print row['name']
     print row['email']



Jan 11, 2019

Python csv

import io
import csv

output = io.BytesIO()
writer = csv.writer(output)

row = ['Name', 'City', 'Phone']
writer.writerow(row)
row1 = ['test1', 'city1', '123456789']
writer.writerow(row1)
row2 = ['test2', 'city2', '234567890']
writer.writerow(row2)
data =  output.getvalue()
fname = "output2.csv"
f = open(fname, 'wb')
f.write(data)
f.close()