我有以下代码
import requests, json
r = requests.get('http://someurl.com/api')
data = r.json()
flights = []
for flight in data:
# print(flight['identifier'])
if flight['STDudt'].strip() < flight['ETDudt'].strip() and flight['OUTudt'].strip() == '':
flights.append(flight)
print(flights)
如何将对象的键作为列名转换为csv文件?
我从代码得到的输出如下:
[{'numGMTDate': '20180515', 'STDudt': '1405', 'STAudt': '1545', 'ETDudt': '1415', 'OUTudt': '', 'OFFudt': ''},{'numGMTDate': '20180515', 'STDudt': '1530', 'STAudt': '1831', 'ETDudt': '1540', 'OUTudt': '', 'OFFudt': ''}]
答案 0 :(得分:0)
我知道解决这个问题的一种方法需要一些工作, 首先将python代码保存到可以轻松设置文件的位置。 现在我对此非常冗长,但可能还有其他方法。
outfile = open ("STRING NAME.csv","w")
将通过“String Name”创建CSV文件.csv将使文件更容易打开
outfile.write(value)
outfile.write(",")
将用逗号分隔所有内容 并且在你想写的每一行的末尾
outfile.write("\n")
将为csv
创建一个新行outfile.close()
完成它
希望这会有所帮助
之前我用过的地方的例子
while h<=math.sqrt(float(d)):
if float(d/(h*h))!=float(int(d/(h*h))):
h=h+1
else:
j=h
h=h+1
if j==int(1) or int(d/(j*j))==1:
a=a
else:
if j/2==int(j/2):
a=a
else:
outfile.write(str(int(b)))
outfile.write(",")
outfile.write(str(int(c)))
outfile.write(",")
outfile.write(str(int(d)))
outfile.write(",")
outfile.write(str(int(g)))
outfile.write(",")
outfile.write(str(int(j)))
outfile.write(",")
outfile.write(str(int(d/(j*j))))
outfile.write(",")
print("b=",int(b)," and c=",c)
print(float(d)," has a square root of ",float(j)," rad ",float(d/(j*j)))
a=a+1
if a==16:
z=input("SO....")
if z==str("good"):
a=16
else:
a=1
print("Fui")
outfile.write("Bad")
outfile.write("\n")
while a==16 and p<10:
outfile.write("\n")
p=p+1
print("new line")
a=1
outfile.close()
答案 1 :(得分:0)
我差不多基于建议重复的代码。唯一的问题是它在每一行之间留下一个空行。
import requests, json
r = requests.get('http://someurl.com/api')
data = r.json()
flights = []
for flight in data:
# print(flight['identifier'])
if flight['STDudt'].strip() < flight['ETDudt'].strip() and flight['OUTudt'].strip() == '':
flights.append(flight)
keys = flights[0].keys()
with open('filteredData.csv', 'w') as output_file:
dict_writer = csv.DictWriter(output_file, keys)
dict_writer.writeheader()
dict_writer.writerows(flights)