Nim: read all content of text file - nim-lang

I liked to read the whole content of a text file using Nim.
I tried
let fileContent: string = readAll("file.txt")
but this doesn't compile.

The readAll proc requires as parameter a File, which is what open returns. However, for a one liner you could use readFile:
let fileContent = readFile("file.txt")

The easist way is to do it this way:
let filepath: string = "file.txt"
let f = open(filepath, fmRead)
let fileContent: string = readAll(f)
f.close()
(nothing has to get imported to do that)

Related

groovy input into file iterate over map

Hi I got the map and loop iterate over the map.
def map = [file.txt : file2.txt,
file3.txt : fil4.txt,
file5.txt : file6.txt]
map.each { k,v ->
collection = new file("k").readLines()
collection2 = new file("v").readLines.findResult()
def commons = collection.intersect(collection2)
}
I want every "commons" collection save into a file, not overwriting this file over the next iterations.
Is there a possibility to do such a thing in the loop?
Suppose you already have your list of files to merge, then the only thing you need to do is to write the lines of each file into the output file, you can do something like this:
def files = ['file1.txt', 'file3.txt', 'file2.txt']
def file = new File('output.txt')
def outputFile = file.newPrintWriter()
def mergeFile = { fileName ->
File sourceFile = new File(fileName)
sourceFile.eachLine{ line ->
outputFile.println(line)
}
}
files.each(mergeFile)
out.close()
This will merge the contents of all your files, there is another thing, you may need to specify the folder of the files, so I suggest to use the constructor that receives the folder.
File output = new File(folder, filename)

Find string and replace line

I already could get a lot of my code together (although it is not a long code). However i am struggeling to achieve the "replace the whole line and not only the search term". Is there like a symbol you can place to do that? Like: * or % etc.
import glob
for files in glob.glob("./prtr/*p*"):
with open(files, 'r') as file:
filedata = file.read()
filedata = filedata.replace('TCPOPTS', 'TCPOPTS = 80\n')
with open(files, 'w') as file:
file.write(filedata)
It works so far that "TCPOPTS" is replaced with "TCPOPTS = 80" and a linebreak is done. But it is not deleting the rest of that line but just moves it to the next line. Which is of course correct due the code. So as mentioned all i need now is to have it not replace the search term but the whole line containing that search term.
Any advice is highly apreciated :)
Kind regards
Edit:
Before:
TCPOPTS = 90
Afterwards:
TCPOPTS = 80
= 90
Expected:
TCPOPTS = 80
I recently solved a very similar task in the following way:
# Scan file
with open(filePath, 'r') as file:
fileContent = file.readlines()
# Find line, where modification should be done
for lineIndex in range(len(fileContent)):
if ('TCPOPTS' in fileContent[lineIndex]):
fileContent[lineIndex] = 'TCPOPTS = 80\n'
with open(filePath, 'w') as tableFile:
tableFile.writelines(fileContent)
break
The benefit of doing it this way is, that the file is not rewritten, if your keyword is not found.
Try using str.startswith
Ex:
import glob
for files in glob.glob("./prtr/*p*"):
res = []
with open(files) as infile:
for line in infile: #Iterate Each line
if line.startswith("TCPOPTS"): #Check if TCPOPTS in line
res.append("TCPOPTS = 80\n")
else:
res.append(line)
with open(files, "w") as outfile: #Write back to file.
for line in res:
outfile.write(line)
You can use re.sub (after importing re) to match the whole line and use back-references to preserve selective portions of the match:
Change:
filedata = filedata.replace('TCPOPTS', 'TCPOPTS = 80\n')
to:
filedata = re.sub(r'^(?P<header>TCPOPTS\s*=\s*).*', r'\g<header>80', filedata, flags=re.MULTILINE)

Multiple transformations of a string with backslashes

I'm getting completely confused with string encodings in Python. I read a number of other answers, but none show, what is really going on in the last three lines of the code below:
filename = "/path/to/file.txt" #textfile contains only the string "\bigcommand"
with open(filename,'r') as f:
file = list(f)
val = file[0] #val = '\\bigcommand\n'
valnew = val.encode('unicode-escape') #valnew = b'\\\\bigcommand\\n'
valnewnew = str(valnew,'utf-8') #valnewnew = '\\\\bigcommand\\n'
Why is the valnew variable suddenly a bytestring? I thought it would be the same as before - but just with the escape characters doubled?
Is there a shorter way to do this, than the convoluted last three lines, in order to get the output of valnewnew?
This will get you the output of valnewnew:
val = file[0].encode('unicode-escape').decode()
with open('t', 'r') as f:
file = list(f)
val = file[0].encode('unicode-escape').decode() # value: '\\\\bigcommand\\n'
When you encode a string in python3.x, you're encoding the string into bytes which then needed to be subsequently decoded to get a string back as a result.
If you give some insight into what you're trying to do, I can try expand.

groovy replace data from file with space

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

How to cut a line in python?

2331,0,13:30:08,25.35,22.05,23.8,23.9,23.5,23.7,5455,350,23.65,132,23.6,268,23.55,235,23.5,625,23.45,459,23.7,83,23.75,360,23.8,291,23.85,186,23.9,331,0,1,25,1000,733580089,name,,,
I got a line like this and how could I cut it? I only need the first 9 variable like this:
2331,0,13:30:08,25.35,22.05,23.8,23.9,23.5,23.7,5455
the original data i save as txt.file, and could I rewrite the original one and save?
Use either csv or just to straight file io with string split function
For example:
import csv
with open('some.txt', 'rb') as f:
reader = csv.reader(f)
for row in reader:
print row[:9]
or if everything is on a single line and you don't want to use a csv interface
with open('some.txt', 'r') as f:
line = f.read()
print line.split(str=",")[:9]
If you have a file called "content.txt".
f = open("content.txt","r")
contentFile = f.read();
output = contentFile.split(",")[:9]
output = ",".join(output)
f.close()
f = open("content.txt","wb")
f.write(output)
If all your values are stored in an Array, you can slice like this:
arrayB = arrayA[:9]
To get your values into an array you could split your String at every ","
arrayA = inputString.split(str=",")

Resources