简体   繁体   English

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

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

I'm trying to delete specific lines in a text file the way I need to go about it is by prompting the user to input a string (a phrase that should exist in the file) the file is then searched and if the string is there the data on that line and the number line number are both stored. 我正在尝试删除文本文件中的特定行,方法是提示用户输入字符串(文件中应存在的短语),然后搜索该文件,然后查找该字符串是否存在该行上的数据和数字行号都被存储。

After the phrase has been found it and the five following lines are printed out. 找到该短语后,将打印出以下五行。 Now I have to figure out how to delete those six lines without changing any other text in the file which is my issue lol. 现在,我必须弄清楚如何删除这六行而不更改文件中的任何其他文本,这是我的问题。

Any Ideas as to how I can delete those six lines? 关于如何删除这六行的任何想法?

This was my latest attempt to delete the 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

Usually I would not think it's desirable to overwrite the source file - what if the user does something by mistake? 通常,我认为不希望覆盖源文件-如果用户错误地执行了操作该怎么办? If your project allows, I would write the changes out to a new file. 如果您的项目允许,我会将更改写到新文件中。

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)

This is also robust to finding the phrase multiple times - it will just start counting lines to remove again. 这对于多次查找该短语也很可靠-它将仅开始计数行以再次删除。

You are appending to your file by using open with 'a'. 您将使用“ a” open附加到文件中。 Also, you are not closing your file (bad habit). 另外,您没有关闭文件(不良习惯)。 str.strip() does not delete the line, it removes whitespace by default. str.strip()不会删除该行,而是默认删除空白。 Also, this would usually be done in a loop. 同样,这通常会循环执行。

This to get started: 这是开始:

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" )

Edit: 编辑:

Read-modify-write solution: 读-修改-写解决方案:

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)

You can find the occurrences, copy the list items between the occurrences to a new list and then save the new list into the file. 您可以找到事件,将事件之间的列表项复制到新列表,然后将新列表保存到文件中。

_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

There are a couple of points that you clearly misunderstand here: 您在这里显然会误解以下几点:

.strip() removes whitespace or given characters: .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.

incrementing i doesn't actually do anything: 增加i实际上没有做任何事情:

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

You're assigning to the i th element of the line, which should raise an exception (that you neglected to tell us about) 您正在分配给该行的第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

Ultimately... 最终...

You have to write to a file if you want to change its contents. 如果要更改其内容,则必须写入文件。 Writing to a file that you're reading from is tricky business. 写入要读取的文件是一件棘手的事情。 Writing to an alternative file, or just storing the file in memory if it's small enough is a much healthier approach. 写入备用文件,或者如果文件足够小则仅将其存储在内存中是一种更健康的方法。

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`

There is a fatal flaw in this approach, though - if the sought after line is any closer than the 6th line from the end, it's going to have problems. 但是,这种方法有一个致命的缺陷-如果所寻求的行距末尾的第6行更近,那就会出现问题。 I'll leave that as an exercise for the reader. 我将其留给读者练习。

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

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