繁体   English   中英

根据用户输入在文件中找到特定行,然后删除特定数量的行

[英]Locate a specific line in a file based on user input then delete a specific number of lines

我正在尝试删除文本文件中的特定行,方法是提示用户输入字符串(文件中应存在的短语),然后搜索该文件,然后查找该字符串是否存在该行上的数据和数字行号都被存储。

找到该短语后,将打印出以下五行。 现在,我必须弄清楚如何删除这六行而不更改文件中的任何其他文本,这是我的问题。

关于如何删除这六行的任何想法?

这是我最近一次删除行的尝试

file = open('C:\\test\\example.txt', 'a')
locate = "example string"
for i, line in enumerate(file):
    if locate in line:
        line[i] = line.strip()
        i = i+1

        line[i] = line.strip()
        i = i+1

        line[i] = line.strip()
        i = i+1

        line[i] = line.strip()
        i = i + 1

        line[i] = line.strip()
        i = i+1

        line[i] = line.strip()
        break

通常,我认为不希望覆盖源文件-如果用户错误地执行了操作该怎么办? 如果您的项目允许,我会将更改写到新文件中。

with open('source.txt', 'r') as ifile:
    with open('output.txt', 'w') as ofile:
        locate = "example string"
        skip_next = 0
        for line in ifile:
            if locate in line:
                skip_next = 6
                print(line.rstrip('\n'))
            elif skip_next > 0:
                print(line.rstrip('\n'))
                skip_next -= 1
            else:
                ofile.write(line)

这对于多次查找该短语也很可靠-它将仅开始计数行以再次删除。

您将使用“ a” open附加到文件中。 另外,您没有关闭文件(不良习惯)。 str.strip()不会删除该行,而是默认删除空白。 同样,这通常会循环执行。

这是开始:

locate = "example string"
n=0
with open('example.txt', 'r+') as f:
    for i,line in enumerate(f):
        if locate in line:
            n = 6
        if n:
            print( line, end='' )
            n-=1

print( "done" )

编辑:

读-修改-写解决方案:

locate = "example string"
filename='example.txt'
removelines=5
with open(filename) as f:
    lines = f.readlines()
with open(filename, 'w') as f:
    n=0
    for line in lines:
        if locate in line:
            n = removelines+1
        if n:
            n-=1
        else:
            f.write(line)

您可以找到事件,将事件之间的列表项复制到新列表,然后将新列表保存到文件中。

_newData = []
_linesToSkip = 3

with open('data.txt', 'r') as _file:
    data = _file.read().splitlines()
    occurrences = [i for i, x in enumerate(data) if "example string" in x]

    _lastOcurrence = 0
    for ocurrence in occurrences:
        _newData.extend(data[_lastOcurrence : ocurrence])
        _lastOcurrence = ocurrence + _linesToSkip 
    _newData.extend(data[_lastOcurrence:])

    # Save new data into the file

您在这里显然会误解以下几点:

.strip()删除空格或给定字符:

>>> print(str.strip.__doc__)
S.strip([chars]) -> str

Return a copy of the string S with leading and trailing
whitespace removed.
If chars is given and not None, remove characters in chars instead.

增加i实际上没有做任何事情:

>>> for i, _ in enumerate('ignore me'):
...  print(i)
...  i += 10
... 
0
1
2
3
4
5
6
7
8

您正在分配给该行的第i个元素,这会引发一个异常(您忽略了这一点,告诉我们)

>>> line = 'some text'
>>> line[i] = line.strip()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

最终...

如果要更改其内容,则必须写入文件。 写入要读取的文件是一件棘手的事情。 写入备用文件,或者如果文件足够小则仅将其存储在内存中是一种更健康的方法。

search_string = 'example'
lines = []
with open('/tmp/fnord.txt', 'r+') as f:  #`r+` so we can read *and* write to the file
    for line in f:
        line = line.strip()
        if search_string in line:
            print(line)
            for _ in range(5):
                print(next(f).strip())
        else:
            lines.append(line)
    f.seek(0)     # back to the beginning!
    f.truncate()  # goodbye, original lines
    for line in lines:
        print(line, file=f)  # python2 requires `from __future__ import print_function`

但是,这种方法有一个致命的缺陷-如果所寻求的行距末尾的第6行更近,那就会出现问题。 我将其留给读者练习。

暂无
暂无

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

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