Python:文件操作错误

时间:2016-11-28 16:18:43

标签: python

我循环浏览json并写入文件并将其传递给另一个使用curl命令上传的功能。 以下是我收到的错误消息:

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

我尝试了不同的方法,但似乎我在这里缺少一些基础知识。任何帮助表示赞赏。

这是我的代码:

#!/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)
    #subprocess.call('cmd', shell=True)
    retval = x.wait()

def main(argv):
    #environment 
    env = sys.argv[1]
    rel_name=sys.argv[2]
    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) ])
    try:
        out_file = open(rel_name,"wb")
        json.dump(newdict,out_file, indent=4)
    finally:
        out_file.close()
    #uploading release json file to BAMS
    upload_file(out_file)

if __name__ == "__main__":
        main((sys.argv[1:]))

1 个答案:

答案 0 :(得分:1)

当您致电upload_file()时,您会传递out_file file而不是string(文件名)。函数open()为第一个参数提供了要打开的文件名。