在不导入任何模块的情况下删除文件中两个字符串之间的所有文本

Delete all text in a file between two strings without importing any modules

由于限制,我不能使用任何导入模块,如 resysos 等。 我一开始必须导入的任何东西都已经用完了。这让我的生活变得一团糟。 这是我到目前为止所得到的:

#I CANT USE ANY IMPORT MODULES DUE TO RESTRICTIONS ON THE MACHINE THIS RUNS ON :(
#
# These Are the Variables for our file path and the start and ending points of what I want to delete.
#----------------------------------------------------------------------------------------------------
DelStart = "//StartBB"
DelEnd = "//EndBB"
FilePath = "C:\Users\kenne_000\Desktop\New folder\test.sqf"
#----------------------------------------------------------------------------------------------------
#Opens the FilePath in Read set this command to f
f = open(FilePath).read()


#Sets value of out to create file in Write mode called "Filepath".out
Out = open(FilePath + '.out', 'w')


#assigns fL as open FilePath and split it up line by line for indexing
fL = f.split('/n')


#Assings LN as index our file and find the lines DelStart and DelEnd
LN = fL.index(DelStart,DelEnd)

#This Gives an error 
#>>> LN = fL.index(DelStart,DelEnd)
#Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
#TypeError: slice indices must be integers or None or have an __index__ method


#text is replacing everything between our start and endpoints with nothing ""
# STILL NEED THIS SECTION NO CLUE HOW TO DO THIS


#Writes our new file Minus our designated start and end points
out.write(text)


#Closes Our New File
out.close()


#Ends Script
Script.close()

我能够创建一个脚本来写入所有文本并插入标记,这些标记对于插入的每组文本都是单独的,但我不再知道在删除时该怎么做标记之间的部分。

这仅使用内置字符串函数:

    string = "This is the string"
    stringA = "This"
    stringB = " string"
    stringC = stringA + stringB
    stringD = stringC.replace(string, stringC)

此答案归功于 lazy1 和他的评论解决方案:

fL is a list of lines. and fL.index will fine a line not part of it. Do you need to delete for every line or for the whole file? In any case, use string index to find start and end then slice away. Something like: i = line.find(DelStart) j = line.find(DelEnd) print line[:i] + line[j+len(DelEnd):]

# These Are the Variables for our file path and the start and ending points of what I want to delete.
#----------------------------------------------------------------------------------------------------
DelStart = "//StartBB" #Replace This With Proper Start Que
DelEnd = "//EndBB" #Replace this with the proper End Que
FilePath = "FILEPATH GOES HERE"
#----------------------------------------------------------------------------------------------------
#Sets Line to open our filepath and read it
line = open(FilePath).read()

#i finds our start place j finds our ending place
i = line.find(DelStart)
j = line.find(DelEnd)


#sets text as finding start and end and deleting them + everything inbetween
text = line[:i] + line[j+len(DelEnd):]

#Creates our out file and writes it with our filter removed
out = open(FilePath + '.out', 'w')
out.write(text)


#Closes Our New File
out.close()


#Ends Script
Script.close()

虽然您的自我回答中的代码看起来应该可以工作,但它并不是特别优雅:

  1. 你真的应该使用 with 块来处理文件。
  2. 您的变量 line 命名错误:它根本不包含一行,而是您输入文件的全部内容。
  3. 您的脚本一次读入整个文件,这对于大文件在内存使用方面可能存在问题。

这是一个替代方案:

def excise(filename, start, end):
    with open(filename) as infile, open(filename + ".out", "w") as outfile:
        for line in infile:
            if line.strip() == start:
                break
            outfile.write(line)
        for line in infile:
            if line.strip() == end:
                break
        for line in infile:
            outfile.write(line)

此函数使用 with open(...)(向下滚动到 "It is good practice to use the with keyword ..." 开头的段落)确保即使您遇到某种错误以及读写错误,文件也能正确关闭一次一行以节省内存。

如果您的文件example.txt包含以下内容:

one
two
three
//StartBB
four
five
six
//EndBB
seven
eight
nine

...然后调用excise()如下...

excise("example.txt", "//StartBB", "//EndBB")

...会做你想做的事:

example.txt.out

one
two
three
seven
eight
nine

重写@KennethDWhite 的回答的重要部分,作为一个函数。我会简单地将其作为对他的回答的评论发布,但格式不正确。

# ToDo: this also deletes the delimiters. Perhaps add a parameeter to indicuate 
#       whether to do so,or just to delete the text between them?
def DeleteStringBetween(string, startDelimiter, endDelimiter):
    startPos = string.find(startDelimiter)
    endPos   = string.find(endDelimiter)

    # If either delimiter was not found, return the string unchanged.
    if (startPos == -1) or (endPos == -1):
        return string

    return string[:startPos] + string[endPos + len(endDelimiter):]