scripting scripting - 1 year ago 71
Python Question

Python: error with file op operations

I am loop through json and writing to file and passing that to another funtion to upload using a curl command.
Here is the error message i am getting:

Traceback (most recent call last):
File "D:\python_ws\", line 33, in <module>
File "D:\python_ws\", line 30, in main
File "D:\python_ws\", line 7, in upload_file
file = open(rel_file).read()
TypeError: coercing to Unicode: need string or buffer, file found

I tried different ways but seems like i am missing some basics here. any help is appreciated.

Here is the my code:

#!/usr/bin/env python
import urllib2,json,sys,requests,subprocess,os

def upload_file(rel_file):
url = "https://localhost:8080/artifactory/list/default.generic.local/ct/releases/"
user = "john.smith"
file = open(rel_file).read()
cmd = 'curl --verbose --user %s --upload-file %s %s' %(user,file,url)
print 'trying to execute %s' % cmd
x = subprocess.Popen('cmd', shell=True)'cmd', shell=True)
retval = x.wait()

def main(argv):
env = sys.argv[1]
consul_url=("http://localhost:9090") % (env)
list_services = "/v1/catalog/services"
services_url = consul_url+list_services
list_of_services = urllib2.urlopen(services_url).read()
each_service = json.loads(list_of_services)
#to remove keys with blank values
newdict = dict([(vkey,vdata) for vkey, vdata in each_service.iteritems() if(vdata) ])
out_file = open(rel_name,"wb")
json.dump(newdict,out_file, indent=4)
#uploading release json file to BAMS

if __name__ == "__main__":

Answer Source

When you call upload_file(), you pass it out_file which is of type file instead of string (file name). The function open() takes for the first argument the file name that you want to open.