我是python的新手,我是如何完成任务的,我在最后一步被阻止了。我在FileA中有时间“ if p ['value'] =='0.04':”。我想在第二次发生时打破循环。因为我在FileA中有30次“ 0.04”。如何打破它。
码:
import glob,os
import sys
import json
import pathlib
import xlwt
wb = xlwt.Workbook()
ws = wb.add_sheet("Excel_resu", cell_overwrite_ok=True)
def main(argv):
for root, dirs, files in os.walk(r'C:\Users\XXX\Desktop\New_Folder'):
for filename in files:
if "FileA.json" in filename:
FileA = (os.path.join(root,filename))
if "FileB.json" in filename:
FileB = (os.path.join(root, filename))
test(FileA, FileB)
def test(FileA,FileA):
count =0
with open(FileA) as json_file:
data = json.load(json_file)
for p in data:
if p['value'] == '0.04':
print(p['Time'])
GetTime = (p['Time'])
with open(FileB) as json_file1:
data1 = json.load(json_file1)
for q in data1:
if q['Time'] == GetTime:
print(q['Gettar'])
resu = q['Gettar']
count = count+1
ws.write(count, 3, resu)
wb.save("Excel.xls")
最佳答案
根据新信息和我们的讨论,尝试使用此代码。它可能会引起一个问题,但是请尝试一下,让我知道,不要忘记在代码中进行相关更改,例如在字典的键等中,它们不应太多
import glob,os
import sys
import json
import pathlib
import xlwt
wb = xlwt.Workbook()
ws = wb.add_sheet("Excel_resu", cell_overwrite_ok=False)
count2=0
def main(argv):
for root, dirs, files in os.walk(r'C:\Users\XXX\Desktop\New_Folder'):
for filename in files:
if "FileA.json" in filename:
FileA= (os.path.join(root,filename))
if "FileB.json" in filename:
FileB= (os.path.join(root, filename))
count2+=1
test(FileA,FileB,count2)
def test(FileA,FileB,count2):
count=0
with open(FileA) as json_file:
data = json.load(json_file)
for p in data:
#print (p)
if p['EgoSpeed'] == '0.04' and count >=1:
pass
elif p['EgoSpeed'] == '0.04' and count ==0:
#print(p['Time'])
GetTime = (p['AdtfTime'])
with open(FileB) as json_file1:
data1 = json.load(json_file1)
for q in data1:
#print(q)
if q['AdtfTime'] == GetTime:
#print(q['Target1_ForwardDist'])
res = q['Target1_ForwardDist']
cols=["B"]
#print(count)
row=ws.row(count2)
for index,col in enumerate(cols):
row.write(index,res)
wb.save("Dilip_test.xls")
if __name__ == "__main__":
main(sys.argv[1:])