我能够使用必要的头创建一个csv文件,然后将其附加到输出中。现在,我想重新打开csv,创建另一个标头,然后根据if
,else
条件向行添加数据。
当我将结果打印到控制台时,我得到了所需的输出(如下所示),但是当我尝试将输出附加到csv文件时,我没有看到相同的结果。
Title: update 1
Added or Deleted Files: True
Title: update 2
Added or Deleted Files: False
Title: update 3
Added or Deleted Files: False
我相信在打开csv文件时如何执行if
条件,但我似乎无法确定我出错的地方。新列Add or Deleted Files
已创建,但添加到其下方行的值与我在控制台中获得的输出不匹配,这是正确的输出。 Added or Deleted Files
列下的输出全部为True
,而不是True
,False
,False
,如控制台输出中所示。拉取请求的Title
列和标题都已正确捕获,新csv文件中的新列也正确捕获,Added or Deleted Files
下的值不正确(如下所示)输出如下)。
Title,Added or Deleted Files
update 1,True
update 2,True
update 3,True
代码包含打印到控制台并输出到csv。在此先感谢您的帮助。它是打开现有csv的最后with open
个语句,创建一个新的,然后添加列,但不正确的行数据给我带来了麻烦。
with open(filename, 'w+', newline='') as f:
csv_writer = csv.writer(f)
csv_writer.writerow(['Title'])
for prs in repo.pull_requests():
getlabels = repo.issue(prs.number).as_dict()
if 'ready-to-merge' in [getlabels['name'] for getlabels in getlabels['labels']] and 'Validation Succeeded' in [getlabels['name'] for getlabels in getlabels['labels']]:
changes = repo.pull_request(prs.number).as_dict()
#print to console statement
print('Title: ', changes['title'])
#output to csv
with open(filename,'a+',newline='') as f:
csv_writer = csv.writer(f)
csv_writer.writerow([changes['title']])
#print to console
if 'added' in (data.status for data in repo.pull_request(prs.number).files()) or 'removed' in (data.status for data in repo.pull_request(prs.number).files()):
print('Added or Deleted Files: True')
else:
print('Added or Deleted Files: False')
#output to new csv with added column and new data
with open(filename, 'r') as csvinput:
with open(filename2, 'w') as csvoutput:
writer = csv.writer(csvoutput, lineterminator="\n")
reader = csv.reader(csvinput)
all = []
row = next(reader)
row.append('Added or Deleted Files')
all.append(row)
for row in reader:
all.append(row)
if 'added' in (data.status for data in repo.pull_request(prs.number).files()) or 'removed' in (data.status for data in repo.pull_request(prs.number).files()):
row.append('True')
else:
row.append('False')
writer.writerows(all)
答案 0 :(得分:1)
您的代码结构已损坏。以下是发生的事情:
因此,您的结果文件在最后一次请求迭代中以整体形式写入,并且该最后一个请求的第二列值被合理地复制到每一行。
您的代码应为:
with open(filename, 'w+', newline='') as f, open(filename2, 'w') as csvoutput:
csv_writer = csv.writer(f)
writer = csv.writer(csvoutput, lineterminator="\n")
row = ['Title']
csv_writer.writerow(row)
row.append('Added or Deleted Files')
writer.writerow(row)
for prs in repo.pull_requests():
...
row = [changes['title']]
csv_writer.writerow(row)
csv_writer.writerow([changes['title']])
...
if 'added' in (data.status for data in repo.pull_request(prs.number).files()) or 'removed' in (data.status for data in repo.pull_request(prs.number).files()):
row.append('True')
else:
row.append('False')
writer.writerow(row)
那是:
repo.pull_requests()