I am new to python and was trying to read a specific column from a CSV file.I am editing the problem now.
Here is the CSV file for eg:
one two three four
1 3 5 7
2 3 5 7
I wrote a very simple Python program as :(thanks to Amrit below for the modified mode).
import csv
with open('Activity_PSR.csv','rU') as csvFile:
reader=csv.reader(csvFile,delimiter=',')
for row in reader:
print row[6]
csvFile.close()
I am getting the specific column with Column header.I want the output of just the elements without the column header.
Once I get the output of this column ,I want to store it in a variable and use it in a CURL command to POST Data. CURL command equiv I beleive is urlib.
Here is the CURL POST Command:
curl -v -X POST -d ‘{“Organization_Id___ORACO__Account_Order":300100051155060,"}' slcaf961.us.oracle.com:10615/crmCommonApi/resources/11.1.10/__ORACO__Order_c
-H "Content-Type:application/vnd.oracle.adf.resourceitem+json" --user “sales_representative”
And the urllib code I am planning to use:
import urllib2
data = '{“Organization_Id___ORACO__Account_Order":300100051155060"}'
url = 'slcad745.us.oracle.com:10618/crmCommonApi/resources/11.1.10/__ORACO__Order_c'
req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
f = urllib2.urlopen(req)
for x in f:
print(x)
f.close()
In the data field here Instead of passing 300100051155060 directly I want to use the value I got from the CSV above and pass that as the Account-Id.
How to pass the value I got from the CSV and pass it to the JSON payload as a parameter ? Need to store the value I got from CSV and store it in a Variable and pass it to the JSON payload/data as a parameter and execute the POST method. Request folks to help me on how to acheive the above scenario
答案 0 :(得分:0)
This means that a row does not have a column on index 2. You need to create a guard:
for row in csv_f:
# make sure row has value on column 2 - otherwise skip row
if len(row) > 2:
print row[2]
You can also use an exception, which in Python is considered cheap:
for row in csv_f:
try:
print row[2]
except IndexError:
print("skipping row %s" % str(row))
If you know all rows need to have a value there, make sure you're using the right delimiter using the delimiter
argument to the reader's constructor.
Also, make sure you're closing the file after the loop:
for row in csv_f:
# do stuff with 'row'
csv_f.close()
答案 1 :(得分:0)
You should consider working with pandas. It has a function called read_csv
that works very well. In your case the code to print out column three is
from pandas import *
csv_f=read_csv('test.csv', sep=r"\s*")
for a in csv_f['three']:
print a
Of course, it has a bunch of functionalities that you should check out and see if you can make an use of.
答案 2 :(得分:0)
请改用此代码:
import csv
with open('test.csv','r') as csvFile:
reader=csv.reader(csvFile,delimiter=',')
reader.next() # if you don't want to print columns headers
for row in reader:
print row[2]
csvFile.close()