Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert line at middle of file with Python?

Tags:

python

Is there a way to do this? Say I have a file that's a list of names that goes like this:

  1. Alfred
  2. Bill
  3. Donald

How could I insert the third name, "Charlie", at line x (in this case 3), and automatically send all others down one line? I've seen other questions like this, but they didn't get helpful answers. Can it be done, preferably with either a method or a loop?

like image 343
tkbx Avatar asked May 08 '12 22:05

tkbx


People also ask

How do you add a line in Python?

In Python, the new line character “\n” is used to create a new line. When inserted in a string all the characters after the character are added to a new line.

How do I put text in a specific position of a file in Python?

seek(count + cn) # place cursor at the correct character location remainder = f. read() # store all character afterwards f. seek(count + cn) # move cursor back to the correct character location f. write(text + remainder) # insert text and rewrite the remainder return # You're finished!

How do you add multiple lines to a file in Python?

Python write multiple lines to file. To write multiple lines to a file in Python, use a with open() function and then the writelines() function. The writelines() method writes the items of a list to the file. The texts will be inserted depending on the file mode and stream position.


2 Answers

This is a way of doing the trick.

with open("path_to_file", "r") as f:     contents = f.readlines()  contents.insert(index, value)  with open("path_to_file", "w") as f:     contents = "".join(contents)     f.write(contents) 

index and value are the line and value of your choice, lines starting from 0.

like image 130
martincho Avatar answered Sep 23 '22 00:09

martincho


If you want to search a file for a substring and add a new text to the next line, one of the elegant ways to do it is the following:

import fileinput for line in fileinput.FileInput(file_path,inplace=1):     if "TEXT_TO_SEARCH" in line:         line=line.replace(line,line+"NEW_TEXT")     print line, 
like image 22
DavidS Avatar answered Sep 22 '22 00:09

DavidS