我有一个脚本,通过API获取json格式的数据。我需要将头文件写入文件,然后附加一些json数据。
import requests, csv, json
def test(limit="", api_token=""):
url_rack = "url"
api_token = "Token " + api_token
headers = {'Authorization': api_token}
params = {'limit': limit}
session = requests.Session()
json_data = session.get(url_rack, headers=headers, params=params)
with open('my_file.csv', 'wb') as csvfile:
filewriter = csv.writer(csvfile, delimiter=',',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
filewriter.writerow(['Header1', 'Header2'])
json_data = json_data.json()['results']
for i in json_data:
bunit = i['tenant']
open(csvfile)
if not bunit:
print 'Placeholder'
else:
bunit = i['tenant']['name']
print bunit
for i in json_data:
owner = i['tenant']
if not owner:
print 'Placeholder Owner'
else:
owner = i['tenant']['name']
print owner
def main():
api_token = "mytoken"
test(api_token=api_token)
if __name__ == "__main__":
main()
我尝试在Header1下的列中编写从for i in tenants:
获取的数据,在Header2下编写来自for i in owners
的数据。我有两个小问题。当我尝试在for循环中打开csv文件时,我收到错误TypeError: coercing to Unicode: need string or buffer, file found
。我知道文件是打开的,所以我不能重新打开它,但是不想在循环中创建它,因为每次迭代都会重写文件?
其次filewriter.writerow
显然是在行中写入,但我需要在标题下的每一列中写入数据。我打印出来测试我可以实际调用api并获取数据,但无法解决如何在Header1和Header2下附加它。
EDIT 我打印的数据:
Placeholder tenant
Placeholder tenant
Tenant1
Placeholder tenant
Placeholder tenant
Placeholder tenant
Placeholder tenant
Tenant2
Placeholder tenant
Tenant3
Tenant4
和
Placeholder Owner
Placeholder Owner
Owner1
Placeholder Owner
Placeholder Owner
Placeholder Owner
Placeholder Owner
Owner2
Placeholder Owner
Owner3
Owner4
答案 0 :(得分:0)
为什么不重写这样的代码:
...
with open('my_file.csv', 'wb') as csvfile:
filewriter = csv.writer(csvfile, delimiter=',',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
filewriter.writerow(['Header1', 'Header2'])
json_data = json_data.json()['results']
for i in json_data:
bunit = i['tenant']
if not bunit:
print 'Placeholder'
else:
bunit = i['tenant']['name']
owner = i['tenant']
if not owner:
print 'Placeholder Owner'
else:
owner = i['tenant']['name']
filewriter.writerow([bunit, owner])
...
答案 1 :(得分:0)
要打开()函数,您需要提供一个文件名作为参数。 在这里,您将提供一个已打开的文件作为参数。因此,第一个错误。
csvfile已经打开,您无需再次打开它来写入它。
要写入文件,您可以将数据存储在列表中,然后在函数结束时写入文件。
假设我想分别在单元格A1,B1,A2,B2,A3,B3中写入r1c1,r1c2,r2c1,r2c2,r3c1,r3c2,那么我会做类似以下的事情: -
listtowrite = [['r1c1','r1c2'],['r2c1','r2c2'],['r3c1','r3c2']]
csvfile = open('my_file.csv', 'w')
for arow in listtowrite:
for acolumn in arow:
csvfile.write(acolumn+',')
csvfile.write('\n')
csvfile.close()
答案 2 :(得分:0)
想出来。只需要将每个写入列表
json_data = prefixes_response.json()['results']
tenant = []
for i in json_data:
bunit = i['tenant']
if not bunit:
tenant.append('Placeholder tenant')
else:
bunit = i['tenant']['name']
tenant.append(bunit)
并压缩两个列表并写入
rows = zip(Header1, Header2)
for row in rows:
filewriter.writerow(row)