Writing a new column in a csv file through Command line - optparse

I want to create a python script that will write a new column in a csv file along with the data through command line, using optparse.
For e.g. if following is the input file(script_name.py) :-
User_ID,Date,Num_1,Num_2,Com_ID
101,2015-04-13,12,21,1011
102,2014-4-3,1,7,1002
then python script_name.py Num_3 1101 1102. will create a new column with data.
Can anybody please direct me somewhere where I can learn how to achieve this ??I already read about OptParse but got nothing.

use
import optparse
parser = optparse.OptionParser()
(options, args) = parser.parse_args()
print args
the args variable will contain an array of all arguments
than using simple loops you can run over the file and add the contents of the args variable

Related

Returning the filename of the current sketch

I am trying to write a GUI that will display the name of the sketch it was generated from using a simple text() command. However, I am running into trouble getting any of the general JS solutions to work for me. Many solutions I have found use the filename reserved word but that does not seem to be reserved in Processing 3.5.4. I have also tried parsing the strings using a similar method to what can be found here. I am very new to processing and this is only my 2nd attempt at using Processing.
Any advice would be greatly appreciated
You can get the path (as a string) to the sketch with sketchPath().
From there you could either parse the string (pull off everything after the last slash) to get the sketch name, or you can use sketchFile() to get a reference to the file itself and get the name from there:
String path = sketchPath();
File file = sketchFile(path);
String sketchName = file.getName();
println(sketchName);
You could combine this all into one line like so:
String sketchName = sketchFile(sketchPath()).getName();

Extracting results from a txt to csv

I am trying to extract some results i've got into a csv file, from a text one.
The results.txt has this form and I wanted to extract it in the following form as csv:
Benchmark, Pass/Fail, ops/m
compiler.compiler, PASSED, 18.37
compress, PASSED, 10.87
crypto.aes, PASSED, 3.91
etc...
So I want to keep only the iteration 1 results, in that form. What would you suggest me to do?
Thank you!
The following Python 2.x script should help to get you started (as was originally tagged). The results.txt file can be passed for lines containing iteration 1 as follows:
import csv
from itertools import ifilter
with open('results.txt', 'rb') as f_input, open('output.csv', 'wb') as f_output:
csv_input = csv.reader(ifilter(lambda x: "iteration 1" in x, f_input), delimiter=' ', skipinitialspace=True)
csv_output = csv.writer(f_output)
csv_output.writerow(["Benchmark", "Pass/Fail", "ops/m"])
for row in csv_input:
csv_output.writerow([row[0], 'PASSED', row[6]])
Creating an output CSV file as follows:
Benchmark,Pass/Fail,ops/m
compiler.compiler,PASSED,18.37
compress,PASSED,10.87
crypto.aes,PASSED,3.91
crypto.rsa,PASSED,8.79
crypto.signverify,PASSED,15.10
derby,PASSED,9.40
mpegaudio,PASSED,7.81
scimark.fft.large,PASSED,4.27
scimark.lu.large,PASSED,0.85
scimark.sor.large,PASSED,2.38
scimark.sparse.large,PASSED,1.46
scimark.monte_carlo,PASSED,5.65
scimark.fft.small,PASSED,8.94
scimark.lu.small,PASSED,8.24
scimark.sor.small,PASSED,12.90
scimark.sparse.small,PASSED,5.61
serial,PASSED,4.53
startup.helloworld,PASSED,41.24
startup.compiler.compiler,PASSED,2.05
startup.compress,PASSED,3.62
startup.crypto.aes,PASSED,0.92
startup.crypto.rsa,PASSED,1.87
startup.crypto.signverify,PASSED,2.76
startup.mpegaudio,PASSED,1.82
startup.scimark.fft,PASSED,4.49
startup.scimark.lu,PASSED,2.44
startup.scimark.monte_carlo,PASSED,1.27
startup.scimark.sor,PASSED,3.14
startup.scimark.sparse,PASSED,1.54
startup.serial,PASSED,1.73
startup.sunflow,PASSED,3.55
startup.xml.transform,PASSED,0.27
startup.xml.validation,PASSED,4.28
sunflow,PASSED,3.69
xml.transform,PASSED,10.41
xml.validation,PASSED,15.37
However, it simply assumes all entries in the file are considered PASSED as there is no example showing what a failed entry would look like in the sample file.

How do I get the index to take the filename as its value?

I have a list of filenames that I want to make (they don't exist yet). I want to loop through the list and create each file. Next I want to write to each file a path (along with other text not shown here) that includes the name of the file. I have written something similar to below so far but cannot see how to get the index i to take the file name values. Please help.
import os
biglist=['sleep','heard','shed']
for i in biglist:
myfile=open('C:\autumn\winter\spring\i.txt','w')
myfile.write('DATA = c:\autumn\winter\spring\i.dat')
myfile.close
Maybe you can try this below python function.
import sys
biglist=['sleep','heard','shed']
def create_file():
for i in biglist:
try:
file_name_with_ext = "C:\autumn\winter\spring\"+ i + ".txt"
file = open(file_name_with_ext, 'a')
file.close()
except:
print("caught error!")
sys.exit(0)
create_file() #invoking the function

how to write formatted text into a file

I was trying to write to a file from textbox input with date:
Here is a part of the code:
DateTime dt=System::DateTime::Now;
System::IO::StreamWriter^ history = gcnew StreamWriter("history.txt");
history->WriteLine(textBox1->Text);
history->WriteLine(dt);
history->Close();
But the output is like this: text
09/02/2015 23:26:07
But I want it to be like:
text 09/02/2015 23:26:07
And also has to append next input to next line of the file.
It's something like a log file.
you use two writeLine and so that write it in 2 Line concat them to write it in one line
history->WriteLine(textBox1->Text);
history->WriteLine(dt);
change this part to
history->write(textBox1->Text);
history->writeLine(dt);
history->WriteLine(textBox1->Text);
Using WriteLine() causes the line break of course. You'd have to use Write() instead. And fret a bit about how you get the extra space between the text and the date, never hesitate to use composite formatting in .NET:
history->WriteLine("{0} {1}", textBox1->Text, System::DateTime::Now);

How to read a file in Groovy into a string?

I need to read a file from the file system and load the entire contents into a string in a groovy controller, what's the easiest way to do that?
String fileContents = new File('/path/to/file').text
If you need to specify the character encoding, use the following instead:
String fileContents = new File('/path/to/file').getText('UTF-8')
The shortest way is indeed just
String fileContents = new File('/path/to/file').text
but in this case you have no control on how the bytes in the file are interpreted as characters. AFAIK groovy tries to guess the encoding here by looking at the file content.
If you want a specific character encoding you can specify a charset name with
String fileContents = new File('/path/to/file').getText('UTF-8')
See API docs on File.getText(String) for further reference.
A slight variation...
new File('/path/to/file').eachLine { line ->
println line
}
In my case new File() doesn't work, it causes a FileNotFoundException when run in a Jenkins pipeline job. The following code solved this, and is even easier in my opinion:
def fileContents = readFile "path/to/file"
I still don't understand this difference completely, but maybe it'll help anyone else with the same trouble. Possibly the exception was caused because new File() creates a file on the system which executes the groovy code, which was a different system than the one that contains the file I wanted to read.
the easiest way would be
new File(filename).getText()
which means you could just do:
new File(filename).text
Here you can Find some other way to do the same.
Read file.
File file1 = new File("C:\Build\myfolder\myTestfile.txt");
def String yourData = file1.readLines();
Read Full file.
File file1 = new File("C:\Build\myfolder\myfile.txt");
def String yourData= file1.getText();
Read file Line Bye Line.
File file1 = new File("C:\Build\myfolder\myTestfile.txt");
for (def i=0;i<=30;i++) // specify how many line need to read eg.. 30
{
log.info file1.readLines().get(i)
}
Create a new file.
new File("C:\Temp\FileName.txt").createNewFile();

Resources