Using groovy to append to a certain line number in a file - groovy

Rather than appending to the end of a file, I am trying to replace or append to a certain line using groovy File manipulation.
Is there a method to do this?
append adds to end of file while write overwrites existing file:
def file = new File("newFilename")
file.append("I wish to append this to line 8")

In general, with Java and Groovy file handling, you can only append to the end of files. There is no way to insert information, although you can overwrite data anywhere without shifting the position of what follows.
This means that to append to a specific line that is not at the end of the file you need to rewrite the whole file.
For example:
def file = new File("newFilename")
new File("output").withPrintWriter { out ->
def linenumber = 1
file.eachLine { line ->
if (linenumber == 8)
out.print(line)
out.println("I wish to append this to line 8")
} else {
out.println(line)
}
linenumber += 1
}
}

For small files you can use the following piece of code:
def f = new File('file')
def lines = f.readLines()
lines = lines.plus(7, "I'm a new line!")
f.text = lines.join('\n')

Related

How to append to a specific line in python without overwriting

I am trying to append to a specific line in a file by checking its first value.
deposit = str(deposit)
with open('Customer Statements.txt','r+') as a:
lines = a.readlines()
for i,line in enumerate(lines):
if line.startswith(loginDetails):
trans = ('{}/Deposit|{}'.format(dt,deposit))
with open('Customer Statements.txt','a') as a:
a.seek(0)
for line in lines:
a.write(line)
break
Please help! This is my code that i tried to make this work but in vain
are you seraching for the "a", append mode?
the code:
with open("file", "a") as f:
f.write("text")
will append the string "text" at the end of the file "file" without deleting the current content of file.
in you case you probably want something close to:
with open('Customer Statements.txt','a') as a:
a.write(deposit)

Lua-filters in Pandoc: replacing string with text from file

Fair warning, I'm rather inexperienced with programming in general.
When generating outputs from markdown documents, my goal is to replace placeholders (e.g. '{{string}}') with text from an external file with the same name (i.e. 'string.md'). I've been able to achieve replacing the string with the first line of text of an .md file.
However, I'm struggling to find a way to replace a string with multiple lines of text (essentially an include function).
The code for the first task was based on some examples from the Pandoc manual:
function file_exists(file)
local f = io.open(file, "rb")
if f then f:close() end
return f ~= nil
end
function lines_from(file)
if not file_exists(file) then return {} end
lines = {}
for line in io.lines(file) do
lines[#lines + 1] = line
end
return lines
end
return {
{
Str = function (elem)
if elem.text:match ("{{.+}}") then
file_name = elem.text:match ("{{.+}}")
file_name = file_name:gsub("{{","")
file_name = file_name:gsub("}}","")
local file = 'lua-filters/'..file_name..'.md'
if not file_exists(file) then
return elem
else
local lines = lines_from(file)
return pandoc.Str(elem.text:gsub("{{.+}}",lines[1]))
end
else
return elem
end
end,
}
}
Every time a place holder '{{string}}' is found, it will be replaced with the first line of the corresponding file 'string.md'. An example:
{{project}} is the project name.
The project number is {{projectno}}.
turns into:
Project Name is the project name.
The project number is 456321.
With a second lua-filter, I want to be able to use a place holder string, where - instead of only the first line - the full content of the text file is returned. However, I've been unable to either find a way to return all lines of the corresponding file (using the same code as above) or convert the content of the file in a more appropriate element.
The desired outcome would be:
## Include section
}}lorem-ipsum{{
Turns into:
## Include section
Lorem ipsum dolor sit amet....
Ut enim ad minim veniam...
With "Lorem ipsum..." being the context of the file 'lorem-ipsum.md'. Using pairs I was only able to return the first line:
if not file_exists(file) then
return elem
else
local lines = lines_from(file)
for k,v in pairs(lines) do
return pandoc.Str(v)
end
Another approach might be to use Para and elem.content[1].text instead of Str and elem.text, but I've been unable to figure out if/how the file should be handled differently.
Any help would be greatly appreciated.

Script to read text file line by line and search for a particular word and copy all the lines related to that word to a remote directory

I have a text file that contains a large number of log list.
I am trying to use a groovy script to read the text file line by line and search for a particular word called DBC. That word "DBC" should be copied to a remote file directory?
You can use the below code for the same. It is just an extended version of what mentioned here Stackoverflow
import java.nio.file.Files;
vOldFilePath = new File("C://TestFiles//ReadFile.txt")
StringWriter vOldFileWriter = new StringWriter();
def vNewFilepath = new File("C://TestFiles//WriteFile.txt")
def vfinalString='';
vOldFilePath.filterLine(vOldFileWriter)
{ vSearchWord ->
if(vSearchWord.contains("DBC")==true)
{
vfinalString= vfinalString+vSearchWord.toString() + "\r\n"
}
}
log.info "Write your data into file"
vNewFilepath.write vfinalString

How to Read the csv file data one by one and put into variable Using Groovy

Here i am facing One problem that. i want to read the csv file data and one by one put it into a variable and that variable i want to assign a next Http Request let say ids.csv file which consisting of values like this
23333
23334
23335
22336
23336
I am using Jsr223 PreProcessor code:
def csvfile = new File('D:/datas/id/ids.csv')
def lines =csvfile.readLines()
lines.each { String line ->
vars.put('Id_value', line.toString())
}
If it is wrong, how to do this with simple code?
You can emulate JMeter CSV data set which add variables with different suffixes, example in tutorial:
String Filename = vars.get("GETfile");
String fileContents = new File(Filename).getText('UTF-8');
def lines = 0 ;
fileContents.eachLine { line ->
lines++;
vars.put("CSVLine_" + lines, line);
}
vars.put("GETfileLength",lines.toString()) ;
and then loop the variables using ForEach Controller:
You need to add a some form of counter to your JMeter Variables reference names, your current code will create only one Id_value variable with the value of 23336, you need to amend it like:
def csvfile = new File('D:/datas/id/ids.csv')
def lines =csvfile.readLines()
lines.eachWithIndex {line, idx ->
vars.put('Id_value_' + idx, line)
}
And you will get:
Id_value_0=23333
Id_value_1=23334
Id_value_2=23335
Id_value_3=22336
Id_value_4=23336
More information:
Groovy Collection.eachWithIndex()
Groovy is the New Black

Python Error with appending string to a file, how do I add it correctly?

I am building a function that opens a file, calculates the sum of integers on different lines, and appends the file with a new string 'Total=sum' on a new line. I am getting error: can't assign to operator on my final value. This is not a duplicate being that I edited the way the duplicate suggestion did and it is still throwing an error. Also, I need to KEEP THE TOTAL, after every iteration.
Here is my function:
def append_total(filename):
total=0
with open(filename) as contents:
for line in contents:
if line.isdigit():
total+=int(line)
else:
total=0
final='Total:'+total+end='\n'
contents.write(final)
return
There are several problems with your code.
1) statement
final = ('Total:', total, end='\n')
has invalid syntax and looks like you just removed print and replaced it with assignment to final. If you want to make string just write something like
final = 'Total:' + str(total) + '\n'
more info about string concatenation at docs
2) you are trying to write in file that was not opened in write mode and furthermore is closed after you leave with statement block. If you want to append a line in the end of existing file you can write
with open(filename, mode='a') as contents:
contents.write(final)
more info about open at docs
3) you need to remove newline symbols from lines to make str.isdigit work as expected, we can do this by using str.strip method
line.strip().isdigit()
4) your accumulated total will be lost in cases when any line is not a digit-like, we can save it from zeroing just by removing else block
Finally your function will be like
def append_total(filename):
total = 0
with open(filename) as contents:
for line in contents:
stripped_line = line.strip()
if stripped_line.isdigit():
total += int(stripped_line)
final = 'Total:' + str(total) + '\n'
with open(filename, mode='a') as contents:
contents.write(final)
(you don't need to explicitly return in the end of every function)
hey it seems to me that you have two "error" in your code:
first you try to write in a close file
second you don't open the file for writting or adding
def append_total(filename):
total=0
with open(filename) as contents:
for line in contents:
if line.isdigit():
total+=int(line)
else:
total=0
with open (filename, 'a') as contents: # a for append w for write
contents.write('Total:{}\n'.format(total))
`
In python when a function return nothing you can spare the return statement
Or if you want to be explicit say return None.
sorry didn't read all the comment but you also have a problem with total
I updated my answer
There are several Problems with your script:
final=('Total:', total, end='\n')
The syntax error comes from end='\n'. You probably rewrote a print() line, but you cannot use that syntax when creating a tuple (which is what you do now).
A better version would be:
final = 'Total:' + total + '\n'
but that would fail, because you cannot "add" a string and an int.
You could use int(total), but using the format method would be even better:
final = 'Total: {}\n'.format(total)
The next problem is, that you try to write to the file after the with block, which will lead to another error. Move the last two lines into the block as well:
def append_total(filename):
total = 0
with open(filename) as contents:
for line in contents:
if line.isdigit():
total += int(line)
else:
total = 0
final = 'Total: {}\n'.format(total)
contents.write(final)
This will still fail, because by default, files are opened read-only. You have to give open() a mode:
with open('blah.txt', 'r+') as contents:
will open the file read/writable and writes will be appended to the end (because you read the whole file before writing).
Further: the total will never be updated, because line contains a '\n' character at the end, and '1\n'.isdigit() will return False. You need to strip() the line before you use it:
line.strip().isdigit():
I also got rid of the final return, which is implicitely added by Python.

Resources