搜索首次出现的字符串,并使用python在上面的行中插入字符串

时间:2019-06-06 23:14:02

标签: python

我通常以bash工作,所以我对这个令人恐惧的python世界非常陌生。

我正在尝试在文件中搜索字符串,然后在该字符串的“首次出现”上方插入文本,并且之间使用空行。

要编辑的文件如下所示:

Name:

Billy

Thorton

Billy

Thorton

我正在尝试在“索顿”上方插入“鲍勃”,并在它们之间插入空行:

Name:

Billy

Bob

Thorton

Billy

Thorton

这是我到目前为止使用的Python。

contents = "Bob"
f = open("file", "w")
contents = "".join(contents)
f.write(contents)
f.close()

这不会搜索字符串,它会替换整个文件。

bash中的一个有效示例为:

sed  -i '0,/Thorton/s//Bob\n\n&/' file

3 个答案:

答案 0 :(得分:1)

在Python中执行此操作的常见方法是打开文件,逐行对其进行迭代并准备结果,然后将结果写入文件。

res = ""

with open("test.txt", "r") as f:
    data = f.readlines() # Read the file line by line

found = False    
for line in data:
    if "Thorton" in line and not found:
        res += "Bob\n\n" # Insert Bob if needed
        found = True
    res += line # Insert the line we just read

with open("test.txt", "w") as f:
    f.write(res) # Write the answer in the same file

答案 1 :(得分:1)

您可以使用str.split()将每个项目放入列表,然后使用list.index()获取"Thorton"的位置,然后再插入str.join()使其可写形式:

with open('filename.txt', 'r') as infile:
    data = infile.read().split()
data.insert(data.index('Thorton'), 'Bob')
with open('filename.txt', 'w') as outfile:
    outfile.write('\n\n'.join(data))

答案 2 :(得分:0)

您可以做到

searchedName = "Thorton"
addedName= "Bob"
f = open("file", "w")
content = f.readlines()
index = content.index(searchedName + '\n')
contents = content.insert(index , addedName + '\n')
contents = "".join(contents)
f.write(contents)
f.close()