简体   繁体   English

Python:向现有的csv文件添加数据的列和行

[英]Python: Adding a column and row of data to exisitng csv file

I am able to create a csv file with the necessary header and then append it with output. 我能够使用必要的标头创建一个csv文件,然后将其附加输出。 Now I would like to reopen the csv, create another header and then add data to the rows based on an if , else condition. 现在,我想重新打开csv,创建另一个标头,然后根据ifelse条件将数据添加到行中。

When I print the results out to console, I get the desired output (as seen below), but when I try to append the output to the csv file, I'm not seeing the same results. 当我将结果打印到控制台时,会得到所需的输出(如下所示),但是当我尝试将输出追加到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

I believe it's how the if condition is executed when opening the csv file, but I can't seem to figure where I'm going wrong. 我相信这是在打开csv文件时执行if条件的方式,但是我似乎无法弄清楚哪里出了问题。 The new column, Add or Deleted Files is created, but the values added to the rows beneath it don't match the output I get in the console, which is the correct output. 创建了新列“ Add or Deleted Files ,但是添加到它下面的行中的值与我在控制台中获得的输出不匹配,这是正确的输出。 The output under the column for Added or Deleted Files are all True and not True , False , False as shown in the console output. 如控制台输出中所示,“ Added or Deleted Files ”列下的输出均为True而不是TrueFalseFalse The Title column and titles of the pull request are all captured correctly as well as the new column in the new csv file, it's the values under Added or Deleted Files that are incorrect (as seen in the output below). 正确捕获了Title列和拉取请求的标题以及新的csv文件中的新列,这是“ Added or Deleted Files下的值不正确(如下面的输出所示)。

Title,Added or Deleted Files
update 1,True
update 2,True
update 3,True

The code contains print to console and output to csv. 该代码包含打印到控制台并输出到csv。 Thanks in advance for any help. 在此先感谢您的帮助。 It's the last with open statements that open the existing csv, creates a new one and then adds the column, but incorrect row data that's giving me trouble. 这是最后一个with open语句的语句,这些语句打开现有的csv,创建一个新的csv,然后添加该列,但是不正确的行数据给我带来麻烦。

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)

The structure of your code is broken. 您的代码结构已损坏。 Here is what happens: 这是发生了什么:

  • open csv file, write header line, close 打开csv文件,写标题行,关闭
  • loop over request 循环请求
    • add request to csv file (by open, append, close) 向csv文件添加请求(通过打开,追加,关闭)
    • open second file and erase it (because of "w" mode) 打开第二个文件并将其删除 (由于使用“ w”模式)
    • for each line in csv 对于csv中的每一行
      • copy field from csv file 从csv文件复制字段
      • copy status of current request 当前请求的复制状态

So your result file was written in totality in last request iteration, and the value of 2nd column for that last request is consistenly copied to every line. 因此,您的结果文件是在上次请求迭代中完全写入的,并且该上次请求的第二列的值始终被复制到每一行。

Your code should be: 您的代码应为:

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)

That is: 那是:

  • open the files once at the beginning of block and only close them at the end. 在块的开始处一次打开文件,仅在结束时将它们关闭。
  • write the two files one row at a time, when processing elements from repo.pull_requests() 处理来自repo.pull_requests()元素时,一次将两个文件写入一行
  • append the second column to row after writing to csv file and before writing to second file. 在写入csv文件之后和写入第二个文件之前,将第二列追加到行中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM