简体   繁体   English

在 Python 中将 TXT 转换为 CSV

[英]Convert TXT to CSV in Python

I would like to convert it into a csv file with header showing Issue number and the row below will be the error name and its directory at the column beside.我想将其转换为 csv 文件,其中 header 显示问题编号,下面的行将是错误名称及其旁边列中的目录。

I have a text file called bucket like this:我有一个名为 bucket 的文本文件,如下所示:

-------------NEW------------------- - - - - - - -新的 - - - - - - - - - -

Issue 1第一期

UVM_FATAL: 1 UVM_FATAL:1

1 test(s) failed with similar error: 1 个测试失败并出现类似错误:

/nfs/disks/ben/rundir/test534 /nfs/disks/ben/rundir/test534

-------------NEW------------------- - - - - - - -新的 - - - - - - - - - -

Issue 2第 2 期

benshi: 4356175.000 ns register error本石:4356175.000 ns 寄存器错误

3 test(s) failed with similar error: 3 个测试失败并出现类似错误:

/nfs/disks/ben/rundir/test234 /nfs/disks/ben/rundir/test234

/nfs/disks/ben/rundir/test321 /nfs/disks/ben/rundir/test321

/nfs/disks/ben/rundir/test123 /nfs/disks/ben/rundir/test123

So far this is what I tried, but it doesn't work.到目前为止,这是我尝试过的,但它不起作用。 Anyone know how to do this?By the way, the Issue wasnt only limited to Issue 1 and 2, it can be going up to infinity depends on the "bucket" text file.任何人都知道如何做到这一点?顺便说一句,问题不仅限于问题 1 和 2,它可以上升到无穷大取决于“桶”文本文件。

bucket = "/nfs/disks/ben/bucket"
inputfile = open(bucket,"r")
bucketreading = inputfile.readlines()
for presence_of_new in bucketreading:
    find_presence_of_new = re.search(r"-------------NEW-------------------",presence_of_new,re.M|re.I)  
    if presence_of_new != 0:
    print "I found NEW!"
    for error_name in bucketreading :
      find_error_name = re.search(r"UVM_FATAL :",error_name,re.M|re.I)
      if find_error_name != 0:
          print_output_to_outfile = open(outfile,"w")
          print_output_to_outfile.writelines(error_name) 
          print_output_to_outfile.close()

Try this code.试试这个代码。 The re.search returns an object if the pattern match, otherwise returns None, so you dont need to compare with 0.如果模式匹配,re.search 返回 object,否则返回 None,因此您不需要与 0 进行比较。

bucket = r"/nfs/disks/ben/bucket"
    inputfile = open(bucket, "r")
    bucketreading = inputfile.readlines()
    for presence_of_new in bucketreading:
        find_presence_of_new = re.search(r"-------------NEW-------------------", presence_of_new, re.M | re.I)
        if find_presence_of_new:
            print("I found NEW!")
        for error_name in bucketreading:
            find_error_name = re.search(r"UVM_FATAL :", error_name, re.M | re.I)
            if find_error_name:
                print_output_to_outfile = open(outfile, "w")
                print_output_to_outfile.writelines(error_name)
                print_output_to_outfile.close()

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

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