Insert Rows on Specific Line in a File

Insert rows on specific line in a file

This has worked for me in the past:

def write_at(fname, at_line, sdat)
open(fname, 'r+') do |f|
while (at_line-=1) > 0 # read up to the line you want to write after
f.readline
end
pos = f.pos # save your position in the file
rest = f.read # save the rest of the file
f.seek pos # go back to the old position
f.write sdat # write new data
f.write rest # write rest of file
end
end

Insert a new line after a specific line number

Just change {3} to {2}to match 2 lines.

  • Find what: (?:.+\R){2}\K
  • Replace with: Insert this sample\n

Insert line at middle of file with Python?

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.

Insert lines in a file starting from a specific line

This can be done with sed: sed 's/fields/fields\nNew Inserted Line/'

$ cat file.txt 
line 1
line 2
fields
line 3
another line
fields
dkhs

$ sed 's/fields/fields\nNew Inserted Line/' file.txt
line 1
line 2
fields
New Inserted Line
line 3
another line
fields
New Inserted Line
dkhs

Use -i to save in-place instead of printing to stdout

sed -i 's/fields/fields\nNew Inserted Line/'

As a bash script:

#!/bin/bash

match='fields'
insert='New Inserted Line'
file='file.txt'

sed -i "s/$match/$match\n$insert/" $file

Inserting Line at Specified Position of a Text File

The best way to make "pseudo-inplace" changes to a file in Python is with the fileinput module from the standard library:

import fileinput

processing_foo1s = False

for line in fileinput.input('1.txt', inplace=1):
if line.startswith('foo1'):
processing_foo1s = True
else:
if processing_foo1s:
print 'foo bar'
processing_foo1s = False
print line,

You can also specify a backup extension if you want to keep the old version around, but this works in the same vein as your code -- uses .bak as the backup extension but also removes it once the change has successfully completed.

Besides using the right standard library module, this code uses simpler logic: to insert a "foo bar" line after every run of lines starting with foo1, a boolean is all you need (am I inside such a run or not?) and the bool in question can be set unconditionally just based on whether the current line starts that way or not. If the precise logic you desire is slightly different from this one (which is what I deduced from your code), it shouldn't be hard to tweak this code accordingly.

Insert a line between existing lines in a CSV file using python

Thanks to @harshal's answer and @Rahib's answer, but I've already tried pandas for a long time, and can't seem to get it to work, looks like it's not really suited for my CSV format.

Finally, I've looked at the posts provided by @Serge Ballesta, and in fact, a simple readlines and the retrieval of the line index is a pretty simple trick:

with open(output) as myFile:
for num, line in enumerate(myFile, 1):
if lookup in line:
index = num

f = open(output, "r")
contents = f.readlines()

value=';'.join(value)
f.close()
contents.insert(index+1, str(value)+'\n')

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

With output being the name of the file (passed in parameters), value being a list of values (joined for a string with ";" as delimiter), and lookup being the string i was looking for (the title row)

Insert or update a row in a text file

One idea would be to skip/ignore/delete the line with today's date (if it exists) and then append a new line with today's date.

Sample data file:

$ cat date.log
2021-08-14, 23.1
2021-08-15, 17.3
2021-08-16, 9.3

$ today=$(date '+%Y-%m-%d')
$ echo $today
2021-08-17

$ newvalue=13.2

One sed idea to implement this logic:

$ sed -i -n -e "/^${today}, .*$/"'!p' -e '$a'"${today}, ${newvalue}" date.log

Where:

  • -i -n -e - -inplace update of source file, -n suppress automatic printing of pattern space, -e designate a piece of script
  • "/^${today}, .*$/" - search for pattern that matches (start of line) + ${today} + , + rest of line; need to use double quotes so that ${today} is replaced with it's actual value
  • '!p' - reverse pattern search and print line (ie, print everything but line that matches ^${today}, .*$); need to use single quotes since !p in double quotes will be replaced with the last history command that started with the letter p
  • -e '$a' - another piece of script that finds end of file ($) and appends the following string; must use single quotes so that bash doesn't try to replace the literal $a with the contents of variable a
  • "${today}, ${newvalue}" - string to append to end of file

If we preface our sed call with set -xv (enable debug mode) we see the following is printed at the console:

+ sed -i -n -e '/^2021-08-17, .*$/!p' -e '$a2021-08-17, 13.2' date.log

And the contents of our file:

$ cat date.log
2021-08-14, 23.1
2021-08-15, 17.3
2021-08-16, 9.3
2021-08-17, 13.2 # new line appended to file

A couple more runs (after issuing set +xv to disable debug mode):

$ newvalue=32.7
$ sed -i -n -e "/^${today}, .*$/"'!p' -e '$a'"${today}, ${newvalue}" date.log
$ cat date.log
2021-08-14, 23.1
2021-08-15, 17.3
2021-08-16, 9.3
2021-08-17, 32.7 # updated (really deleted and appended)

$ newvalue=73.xxx
$ sed -i -n -e "/^${today}, .*$/"'!p' -e '$a'"${today}, ${newvalue}" date.log
$ cat date.log
2021-08-14, 23.1
2021-08-15, 17.3
2021-08-16, 9.3
2021-08-17, 73.xxx # updated (really deleted and appended)

$ today='2021-09-23'
$ newvalue=7.25
$ sed -i -n -e "/^${today}, .*$/"'!p' -e '$a'"${today}, ${newvalue}" date.log
$ cat date.log
2021-08-14, 23.1
2021-08-15, 17.3
2021-08-16, 9.3
2021-08-17, 73.xxx
2021-09-23, 7.25 # new line appended to file


Related Topics



Leave a reply



Submit