如何在python中修改文本文件

时间:2017-05-15 06:57:19

标签: python

我有一个类似示例的文本文件: 小例子:

@

当你看到@之后的一行是一系列字符时。每4行也与一个ID相关。在某些情况下,@M00872:361:000000000-D2GK2:1:1101:16003:1351 1:N:0:1 ATCCGGCTCGGAGGA + 1AA?ADDDADDAGGG @M00872:361:000000000-D2GK2:1:1101:15326:1352 1:N:0:1 GCGCAGCGGAAGCGTGCTGGG + CCCCBCDCCCCCGGEGGGGGG 之后的行是一个空格。如果是这种情况,我想删除所有4 类似ID下的行。 $(function() { var iframe = $('#video')[0]; console.log() var player = $f(iframe); // When the player is ready, add listeners for pause, finish, and playProgress player.addEvent('ready', function() { status.text('ready'); player.addEvent('pause', onPause); player.addEvent('finish', onFinish); player.addEvent('playProgress', onPlayProgress); }); // Call the API when a button is pressed $('button').bind('click', function() { player.api($(this).text().toLowerCase()); }); function onPause() {} function onFinish() {} function onPlayProgress(data) { if (data.seconds >= 20) { $('.show--div-20sec').css('display', 'block') } } });行也是每个ID的第一行。

结果为小例子

.button {
  width: 48px;
  height: 48px;
  cursor: pointer;
}

.defs {
  position: absolute;
  top: -9999px;
  left: -9999px;
}

iframe {
  float: left;
  width: 350px;
  height: 200px;
}

.buttons {
  padding: 1rem;
  background: #f06d06;
  float: left;
}

body {
  padding: 1rem;
}

.show--div-20sec {
  width: 100%;
  background: red;
  height: 80px;
  float: left;
  display: none;
}

1 个答案:

答案 0 :(得分:0)

使用fileinput模块的解决方案(用于修改文件):

import fileinput

with fileinput.input(files="file.txt", inplace=True, backup="file.bak") as f:
    for l in f:
        if l.strip().startswith("@"):
            c = 2
            next_line = f.readline().strip()  # reading next line (line afer `@` line)
            if not next_line:   # if next line is empty
                while c:        # skip rest 2 lines
                    c -= 1
                    try:
                        next(f)
                    except StopIteration:
                        break
            else:
                # printing valid 4 lines
                print(l.strip())
                print(next_line.strip())
                while c:
                    c -= 1
                    try:
                        print(next(f).strip())
                    except StopIteration:
                        break

生成的文件内容:

@M00872:361:000000000-D2GK2:1:1101:16003:1351 1:N:0:1
ATCCGGCTCGGAGGA
+
1AA?ADDDADDAGGG
@M00872:361:000000000-D2GK2:1:1101:15326:1352 1:N:0:1
GCGCAGCGGAAGCGTGCTGGG
+
CCCCBCDCCCCCGGEGGGGGG