Is there a way to do this? Say I have a file that's a list of names that goes like this:
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?
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.
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!
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.
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.
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,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With