I want to replace a specific value with an integer in a text value. Seems like I am missing something important.
x=5
def file = new File('/Users/path/name.txt')
def newConfig = file.text.replace('abc',x)
file.text = newConfig
tried x.toString() but did not help either.
I am using this code to generate a number, and need that number to be replaced within a .json file.
Thank you
Let's say we have a file with the following string:
testabcandanotherabc
abcandabcandanotherabc
I use the following code:
x = 5
def file = new File('/Users/path/name.txt')
def newConfig = file.text.replaceAll('abc', x.toString())
file.write(newConfig)
It changes the file content as following:
test5andanother5
5and5andanother5
I hope it will help.
Related
How can I pass a excel/csv file as a function parameter?
I have wrote a piece of code to copy content from one excel file to another excel file. Now I want to define it as a function so I just have to mention file name from which I want to transfer data to my existing file.
Thanks a lot in advance.
I am very new to Python Programming, and looking forward to learn a lot.
def feed_input_file(InputFile):
InputFile = "D:\\Python_Projects\\ABC.xlsx" #(I am passing Input file at the moment but I don't wanna pass it here)
#( Here I am trying to call my function parameter value)
Workbook1 = xl.load_workbook(feed_input_file(InputFile))
............
Still not quite sure what you are trying to do but if you want to create a function that will take a filename as an argument you could try something along the lines of:
def processFile(fn:str):
#Reads in the contents of file specified by fn
content = ''
with open(fn, 'a') as f:
data = f.read()
#Do something with data here to create content
return content
Then in your main part of the script
for filename in listofFiles:
fle_out = processFile(filename
#Do something here with file contents
i have a text file i want to remove punctuation and save it as a new file but it is not removing anything any idea why?
code:
def punctuation(string):
punctuations = '''!()-[]{};:'"\,<>./?##$%^&*_~'''
for x in string.lower():
if x in punctuations:
string = string.replace(x, "")
# Print string without punctuation
print(string)
file = open('ir500.txt', 'r+')
file_no_punc = (file.read())
punctuation(l)
with open('ir500_no_punc.txt', 'w') as file:
file.write(file_no_punc)
removing any punctuation why?
def punctuation(string):
punctuations = '''!()-[]{};:'"\,<>./?##$%^&*_~'''
for x in string.lower():
if x in punctuations:
string = string.replace(x, "")
# return string without punctuation
return string
file = open('ir500.txt', 'r+')
file_no_punc = (file.read())
file_no_punc = punctuation(file_no_punc)
with open('ir500_no_punc.txt', 'w') as file:
file.write(file_no_punc)
Explanation:
I changed only punctuation(l) to file_no_punc = punctuation(file_no_punc) and print(string) to return string
1) what is l in punctuation(l) ?
2) you are calling punctuation() - which works correctly - but do not use its return value
3) because it is not currently returning a value, just printing it ;-)
Please note that I made only the minimal change to make it work. You might want to post it to our code review site, to see how it could be improved.
Also, I would recommend that you get a good IDE. In my opinion, you cannot beat PyCharm community edition. Learn how to use the debugger; it is your best friend. Set breakpoints, run the code; it will stop when it hits a breakpoint; you can then examine the values of your variables.
taking out the file reading/writing, you could to remove the punctuation from a string like this:
table = str.maketrans("", "", r"!()-[]{};:'\"\,<>./?##$%^&*_~")
# # or maybe even better
# import string
# table = str.maketrans("", "", string.punctuation)
file_with_punc = r"abc!()-[]{};:'\"\,<>./?##$%^&*_~def"
file_no_punc = file_with_punc.lower().translate(table)
# abcdef
where i use str.maketrans and str.translate.
note that python strings are immutable. there is no way to change a given string; every operation you perform on a string will return a new instance.
This is probably very basic question but I am unable to find any solution (or I am poor at finding one)- tried for 1 entire day.
I have a text file. I want to read in column-by-column. The file looks something like this (e.g.):
#no&glon&glat&fwhm1&fwhm2&comments\\
1&90&30&-&3&some\\
2&89&31&4&7&commnts\\
3&87&32&6&9&\\
4&88&33&1&4&\\
5&84&23&-&-&\\
Missing values are represented with "-". Each line ends with "\\". I need this because ultimately i export the entire table to Latex.
Program goes like this:
`data = np.genfromtxt('test.txt',comments='#',delimiter = '&', missing_values = '-', usecols = (0,1,2,3,4))
no = d[:,0]
glon = d[:,1]
glat = d[:,2]
fwhm1 = d[:,3]
fwhm2 = d[:,4]
value1 = fwhm1 * 1.29
value2 = fwhm2 * 0.8 `
Now, I want to store them again (with value1 and value2) column-by-column in another file (text or csv) with '&' as delimiter. How do it do it?
I tried the following but failed in Python3
F = open('test.txt','w')
for i in range(0,len(no)):
print >> F, '{:20f}{:20f}{:20f}'.format(no[i],value1[i],value2[i])
Help is greatly appreciated.
Thanks in advance.
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
i want to replace string from a file.
i have a line like this:
qwe{data:"dede-dddd-ssss",login:"user",display:"screen"},abc,xyz
i want to replace all string starting from data to login with spaces
i try this i can only replace the string, is there a way to replace with a starting and endpoint for string?
def source = new File("c:\\sq\\file1.txt")
def dest = new File("c:\\sq\\file2.txt")
def fileText = source.text
def filedest = dest.text
for ( index in 1..9 ) {
fileText = (fileText =~ /data/).replaceFirst("")
This code has an anchored version (to {) of the regex:
def fileText = '''\
qwe{data:"dede-dddd-ssss",login:"user",display:"screen1"},abc,xyz
...
qwe{data:"data2",login:"user2",display:"screen2"},abc,xyz
...
qwe{data:"data3",login:"user3",display:"screen3"},abc,xyz\
'''
fileText = fileText.replaceAll(/(?<=\{)\s*data:[^,]+,\s*login:[^,]+,/ , '')
println fileText
Output:
qwe{display:"screen1"},abc,xyz
...
qwe{display:"screen2"},abc,xyz
...
qwe{display:"screen3"},abc,xyz
Try also in the online groovy web console
UPDATE
If a understand correctly your request: this following code read the input text from source (c:\\sq\\file1.txt) and put the modified text into destination file dest (c:\\sq\\file2.txt):
def source = new File("c:\\sq\\file1.txt")
def dest = new File("c:\\sq\\file2.txt")
dest.write(source.text
.replaceAll(/(?<=\{)\s*data:[^,]+,\s*login:[^,]+,/ , '') )
If you want it in the files, then you can try below, and find the updated data in test2.txt:
note:please update the file paths as per your environment
Courtesy #GsusRecovery for regex
def fileContent = new File('/tmp/test.txt').text
def replacedContent = fileContent.replaceAll(/(?<=\{)\s*data:[^,]+,\s*login:[^,]+,/ , '')
def newFile = new File('/tmp/test2.txt')
newFile.write(replacedContent)
I'm not entirely clear on what your desired outcome is. If you want to remove the "data" and "login" fields and the corresponding values from the input strings, such that your example of:
qwe{data:"dede-dddd-ssss",login:"user",display:"screen"},abc,xyz
becomes:
qwe{display:"screen"},abc,xyz then you can easily use a regex to do this.
The following code:
String str = """qwe{data:"dede-dddd-ssss",login:"user",display:"screen"},abc,xyz"""
str = str.replaceFirst("data.*login:\".+?\",", '')
println str
Prints qwe{display:"screen"},abc,xyz