[英]how to Use python to find a line number in a document and insert data underneath it
Hi I already have the search function sorted out: 嗨,我已经整理好了搜索功能:
def searchconfig():
config1 = open("config.php", "r")
b='//cats'
for num, line in enumerate(config1,0):
if b in line:
connum = num + 1
return connum
config1.close()
This will return the line number of //cats, I then need to take the data underneath it put it in a tempoary document, append new data under the //cats and then append the data in the tempoary document to the original? 这将返回// cats的行号,然后我需要将其下面的数据放入临时文档中,在// cats下附加新数据,然后将临时文档中的数据附加到原始文档中? how would i do this? 我该怎么办? i know that i would have to use 'a' instead of 'r' when opening the document but i do not know how to utilise the line number. 我知道打开文档时必须使用“ a”而不是“ r”,但我不知道如何利用行号。
I think, the easiest way would be to read the whole file into a list of strings, work on that list and write it back afterwards. 我认为,最简单的方法是将整个文件读入字符串列表,在该列表上进行处理,然后再写回去。
# Read all lines of the file into a list of strings
with open("config.php", "r") as file:
lines = list(file)
file.close()
# This gets the line number for the first line containing '//cats'
# Note that it will throw an StopIteration exception, if no such line exists...
linenum = (num for (num, line) in enumerate(lines) if '//cats' in line).next()
# insert a line after the line containing '//cats'
lines.insert(linenum+1, 'This is a new line...')
# You could also replace the line following '//cats' like
lines[linenum+1] = 'New line content...'
# Write back the file (in fact this creates a new file with new content)
# Note that you need to append the line delimiter '\n' to every line explicitely
with open("config.php", "w") as file:
file.writelines(line + '\n' for line in lines)
file.close()
Using "a"
as mode for open
would only let you append ath the end of the file. 使用"a"
作为open
模式只会让您附加文件末尾。
You could use "r+"
for a combined read/write mode, but then you could only overwrite some parts of the file, there is no simple way to insert new lines in the middle of the file using this mode. 您可以将"r+"
用于组合的读/写模式,但随后只能覆盖文件的某些部分,没有简单的方法使用此模式在文件中间插入新行。
You could do it like this. 您可以这样做。 I am creating a new file in this example as it is usually safer. 我在此示例中创建一个新文件,因为它通常更安全。
with open('my_file.php') as my_php_file:
add_new_content = ['%sNEWCONTENT' %line if '//cat' in line
else line.strip('\n')
for line in my_php_file.readlines()]
with open('my_new_file.php', 'w+') as my_new_php_file:
for line in add_new_content:
print>>my_new_php_file, line
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.