Python:与文件操作操作有关的错误
问题描述:
我通过json循环并写入文件并将其传递给另一个使用curl命令上载的函数。 以下是错误消息我得到:Python:与文件操作操作有关的错误
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:]))
答
当你调用upload_file()
,你通过它out_file
这是file
而不是string
(文件名)类型。函数open()
需要为第一个参数指定要打开的文件名。
+0
谢谢。我纠正了它。好像我没有收到CURL命令的回应。 – ryan1506
如果您要发布Python代码,请确保正确地重现您的缩进。严重缩减的Python代码是无稽之谈。 – khelwood
谢谢。我会确保这样做。 – ryan1506