简体   繁体   English

如何使用python在文档中查找行号并在其下插入数据

[英]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.

相关问题 如何在csv文件python中的特定列下插入数据 - How to insert data underneath a specific column in csv file python 如何在Python中查找光标的行号? - How to find line number of cursor in Python? 如何在python中找到文件结尾的行号? - How to find the line number of the end of file in python? 如何在python中查找列表的序列号(如行号1、2) - How to find sequence number of list in python (like line number 1, 2) 如何使用 Python 将一组文本插入文件的特定行号 - How to insert a set of text to a particular line number of a file using Python Python:如何在数据列中查找最高编号 - Python: How to find the highest number in a column of data Python - 使用列表将数据插入到 Word 文档中 - Python - Insert data into a word document using a list Python - 在文档之间插入熊猫数据框 - Python - Insert pandas data frame in between of the document 在 Python 中,如何逐行读取文本文档并在每行末尾打印一行中相同字符的数量? - In Python, how can I read a text document line-by-line and print the number of same characters in a row at the end of each line? 如何在 Tkinter 文本框中查找搜索字符串的行号,然后在之前插入字符串 - How to find line number of searched string in Tkinter Textbox and then insert string just before
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM