【问题标题】:readlines from iterating through an array and writelines to a new filereadlines 从遍历数组和 writelines 到新文件
【发布时间】:2018-12-05 01:05:17
【问题描述】:

bad_list 是一个从不同函数返回的数组,返回有问题且需要仔细查看的行的行号

例如array([ 1, 3, 4, 27, 50, 99], dtype=int64)


想法是阅读test.txt,并制作一个新的test_badlines.txt,其中只包含bad_list中指定的有问题的行


这是我目前所拥有的,打印行有效,但写入行在应该是 6 行时只吐出 1 行

for rows in bad_list:
    filename = 'C:\\Users\\Username\\Downloads\\test.txt'
    bad_filename = str(filename)[:-4] + '_badlines.txt'
    with open(filename) as f,  open(bad_filename, 'w') as wt: 
        lines = f.readlines()
        #print lines[rows]
        wt.writelines(lines[rows])

【问题讨论】:

    标签: python python-2.7 readlines


    【解决方案1】:

    lines 是一个普通的list,而普通的lists 不能被一系列要查找的索引索引。这里最简单的解决方案是创建一个生成器表达式,提取您关心的行,替换:

    wt.writelines(lines[rows])
    

    与:

    wt.writelines(lines[row] for row in bad_list)
    

    假设bad_list 是您描述的数组,您完全放弃外部for 循环;您不想每行一遍又一遍地打开输入和输出文件,总共只打开一次。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-03
      • 2021-11-16
      • 1970-01-01
      • 2020-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多