Read and write the file in terms of lines: var allLines = File.ReadAllLines("MyFile"); allLines[0] = "2345"; File.WriteAllLines("MyFile", allLines); ...
python,arrays,file-io,text-files
You already have filled fileRecord and fileScores. Now you combine them and sort: >>> fileRecord = ['Raj,Joy', 'Smith,John', 'Campbell,Michelle'] >>> fileScores = [[9, 8, 1], [8], [5, 7, 9]] >>> comb = [] >>> for record, scores in zip(fileRecord, fileScores): ... for score in scores: ... comb.append((record, score)) ... >>>...
You may use xml module, which is very closed to your file structure: s = ''' <counter name="abcb">70324360</counter> <counter name="efghij">1094</counter> <counter name="klm">0</counter>''' import xml.etree.ElementTree as ET tree = ET.fromstring('<root>' + s + '</root>') def get_counter(name): for node in tree.iter('counter'): if node.attrib.get('name') == name: return node.text Usage: get_counter('klm') '0' In case...
vb.net,winforms,text-files,streamreader
There is no way to know how many lines a file has without opening the file and reading its contents. You didn't indicate how far you've got on this. Do you know how to open a file? Here's some basic code to do what you want. (Sorry, this is C#...
python,file,python-3.x,io,text-files
unique = str(unique) + i + " " + str(newWords.count(i)) + "\n" The line above, is appending at the end of the existing set - "unique", if you use some other variable name instead, like "var", that should return correctly. def uniqueFrequency(newWords): '''Function returns a list of unique words with...
when i run my code i get the following ./todo.sh: line 25: syntax error near unexpected token else' ./todo.sh: line 25: else' You must use parentheses to define a shell function, but they have no part in calling one. A shell function is invoked just like any other command:...
File.Exists returns a Boolean indicating whether a file at a certain path exists: If File.Exists(pathToFile) Then ... End If Be sure to include Imports System.IO at the top of your source code file....
You can do that by using pattern matching. Here the solution: public static void main(String[] args) { String newString = "[{124}, {126}, {12, 14}, {13, 18, 130, 113}]"; Pattern p = Pattern.compile("\\{(.*?)\\}"); Matcher m = p.matcher(newString); while(m.find()) { System.out.println(m.group(1).replace(",", "")); } } The output will be: 124 126 12 14...
The problems with your code are: you repeat yourself unecessarily except: pass is always wrong platform.os is not a function type The concise and correct version of the code is import platform with open("reportLog.txt", "w") as log: log.write("####REPORT####\n") names = """dist system platform mac_ver dist node architecture machine processor""".split() for...
The problem lies with the 'r+' mode. When you use 'r+' you can read and write, sure, but it's up to you to control where in the file you write. What's happening is you read the file, and the cursor is stuck at the end, so when you write it...
You can save your text file in "Assets" folder of project and use following code to retrieve that file in java class try { reader = new BufferedReader( new InputStreamReader(getAssets().open("YOUR_TEXT_FILE.txt"))); StringBuilder total = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { total.append(line); } message=total.toString(); System.out.println(message); } catch...
java,arrays,table,text-files,padding
In the code below change append with StringBuilder with BufferedWriter. public void appendCentered(StringBuilder sb, String s, int width) { if (s.length() > width) { s = s.substring(0, width); } int spaces = width - s.length(); int before = spaces / 2; int after = spaces - before; // Could be...
python,dictionary,append,text-files
When you print the scores at the end, you're looking them up via the variable worker which doesn't change in your loop, rather than name.
This might work for you (GNU sed): sed -ri '10,15!b;10h;10!H;15!d;x;s/^([^\n]*)(.*\n)(.*)/\3\2\1/' f1 f2 fn This stores a range of lines in the hold space and then swaps the first and last lines following the completion of the range. The i flag edits each file (f1,f2 ... fn) in place....
c++,multidimensional-array,text-files
This should get you going: #include <fstream> #include <vector> #include <iostream> #include <string> struct XY { int x; int y; }; using std::ifstream; using std::vector; using std::cerr; using std::endl; using std::string; int main() { vector<XY> data; ifstream input("filename.txt"); if (input.good()) { int skip; string troncons; int numLines; input >> skip;...
python,file,sorting,text-files,average
EDIT: Updated the answer, after understanding what user was trying to do. The first issue I have with this code is that it is very redundant. Python follows DRY (Do not Repeat Yourself) approach. Take the redundant code and create a function out of it and call the function multiple...
ClassNames = studentname and score most likely sets the variable ClassNames to score which sounds like it could by of int. By calling if studentname not in ClassNames: ... you iterate through ClassNames to find studentname, but like your error says, int is not iterable. Further problems: list.append() works inplace...
python,file,matplotlib,plot,text-files
import matplotlib.pyplot as plt with open("m.txt") as m: for index, line in enumerate(m): m_float = map(float,line.strip()) plt.plot(index, m_float,'bo') plt.ylabel('FLOC - % of line') plt.xlabel('Sample Number') plt.axis([-10,10,0,5]) plt.show() I replaced split with strip for clarity. Notice, that I added enumerate to get numbers with their indices. Later I pass them to...
javascript,download,zip,text-files
just use some JavaScript zip library eg https://stuk.github.io/jszip/ and a file saver https://github.com/eligrey/FileSaver.js/. jszip provides all necessary examples to put files into the zipfile (this covers points 1 and 2). Using FileSaver.js is also pretty straightforward as for point 3....
Assuming the data is consistent and I'm also assuming the GCells will come before GTrx line (since GTrx is referencing the id of the GCell), then you could create a simple parser for doing this and store the values in a dictionary. First thing to do is create a class...
matlab,machine-learning,text-files
The problem, as you've probably realized by now, is that csvread() only works for numeric values. Instead you need to use textscan() to deal with strings / characters. Try this: fileID = fopen('abalone.data'); data = textscan(fileID,'%s %*[^\n]', 'Delimiter',','); fclose(fileID); labels = cell2mat(data{1}); This will open the file and read in...
android,arrays,string,sharedpreferences,text-files
For the file, if you want spaces in between weights, add a space when writing to file. Change this: osw.write(Double.toString(weight)); to this: osw.write(Double.toString(weight) + " "); It will result in: 10.0 20.0. Something to be aware of is that now there is going to be a space after the last...
vb.net,visual-studio-2010,text-files
You have created a DirectoryInfo object for the folder. You can use the GetFiles method to get all the files with an extension of .RTO, and append them to the RichTextBox like this: Dim FilePath As DirectoryInfo = New DirectoryInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Employee Record\" & TextBox1.Text)) RichTextBox1.Clear 'omit this line if you...
It seems that using SharedPreferences would be better suited for this task. See this post: Saving high scores in Android game - Shared Preferences Documentation: http://developer.android.com/reference/android/content/SharedPreferences.html...
Try the column command like column -t -s',' This is what I can get quickly. See the man page for details....
python,text-files,manipulation,extraction
One way of doing this, without the installation of third-party modules like numpy/pandas, is as follows. Given an input file, called "input.csv" like this: a,b,c_net,d,e_net 0,0,1,0,1 0,0,1,0,1 (remove the blank lines in between, they are just for formatting the content in this post) The following code does what you want....
In Bash you can do this: #!/bin/bash declare -a varA varB while IFS=$'\t' read -r num first second;do varA+=("$first") varB+=("$second") done <file echo ${varA[1]} ${varB[1]} You can access each element of varA array using index ${varA[$index]} or all of them at once with ${varA[@]}....
java,android,android-studio,text-files
Why not use sharedpreferences? SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(app); // get the current in value or 0 if it's not set int anInt = preferences.getInt("MY_INT", 0 /* default value */); // blah // save the incremented int. preferences.edit().putInt("MY_INT", anInt++).commit(); ...
The error is "Input string was not in a correct format", which tells me that at least one value of colourRead is not an integer value. int.Parse ignores whitespace, so it isn't a matter of formatting. It cannot be a simple integer value and has to contain another character like...
The first optimization is to read the whole file in memory in one shot. Accessing memory in the loops will be faster than calling fread. The second optimization is to do less arythmetic operations, even if it means more code. Third optimization is treating the data from file as characters...
Update your text file contains string, entries seprated by line brakes and values by three spaces (actually html coded spaces). Here we read whole txt file in,(some could do this line by line): $whole_string = file_get_contents('data.txt'); So firstly we get each line: $entries = explode('\n',$whole_string); Then value arrays are pushed:...
matlab,text-files,carriage-return
importdata is the most suitable function. Assuming you have a file like that: import = importdata('data.txt','',3) data = import.data returns: data = 1 2 3 4 5 If you have multiple columns you can specify a delimiter: importdata('data.txt','\t',3) but for just one column it doesn't matter....
java,arraylist,text-files,group,information-retrieval
I think, the datastructure that suits your (described) needs best is a MultiMap. It is like a map, but with the possibility to store more than one value for a key. For example the implementation from the guava project. http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Multimap.html First, you have to iterate over the arraylist: final Multimap<String,...
Your code has some problems: fName is declared as char fName[10]; and you use sprintf(fName,"bodies%d.txt",i); which writes 12 characters into fName(including the NUL-terminator) which can atmost hold 9 characters(+1 for the NUL-terminator). The for loop: for (j = count; j < num; j++) { fscanf(fp, "%f%*c %f%*c %f%*c", &b[j].x, &b[j].y,...
linux,bash,shell,grep,text-files
Use grep -F to treat the search pattern as a fixed string. You could also replace wc -l with grep -c. grep -cF ",[" loaded.txt > newloaded.txt If you're curious, [ is a special character. If you don't use -F then you'll need to escape it with a backslash. grep...
text-files,extract,large-files,data-files
Install[1] Babun Shell (or Cygwin, but I recommend the Babun), and then use sed command as described here: How can I extract a range of lines from a text file on Unix? [1] Installing Babun means actually just unzipping it somewhere, so you don't have to have the Administrator rights...
dashes() is void returning function how will you get this line? fprintf (ecoli_Report,"%c",dashes()); If you need to print the line in the file, make the prototype and call like this, void dashes(FILE *fp){ fprintf(fp,"------------------\n"); } Remove this line. fprintf (ecoli_Report,"%c",dashes()); And change that calling into like this, dashes(ecoli_Report); Or else...
Replace this line: with open( 'Green Bottles.txt', 'w') as a: With with open(numbers[num1] + ' Green Bottles.txt', 'w') as a: This will prepend your file name with the appropriate word....
java,search,text-files,java.util.scanner
Can you once try this method with slight change? public static void parseFile(String s) throws IOException { File file = new File("data.txt"); Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { final String lineFromFile = scanner.nextLine(); if (lineFromFile.contains(s)) { System.out.println(scanner.nextLine()); // code hangs right here. } } } Once it finds...
vb.net,visual-studio-2010,text-files
You can loop through the lines and skip the ones that are blank. The following code skips lines that are empty or only contain white space. If you only want to skip empty lines, change IsNullOrWhiteSpace to IsNullOrEmpty. Dim FileName = New DirectoryInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "CLIENT HISTORY\" & TextBox1.Text)) For Each ClientDetailsCHT...
java,string,swing,text-files,jcombobox
Using the code which you linked to, you could alter it to do something like this: private void populateCols(int a1, int a2, int b1, int b2) { String[] lines; lines = readFile(); jComboBox1.removeAllItems(); for (String str : lines) { jComboBox1.addItem(str.substring(a1, a2) + " " + str.substring(b1, b2)); } } ...
Why not try: Dim ti2 = (Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Customers\" & TextBox1.Text)) Dim du = Path.Combine(ti2, TextBox1.Text, TextBox2.Text, TextBox3.Text + ".txt") ...
You could use output redirection cat newtodo.txt > todo.txt <br> or You could rename newtodo.txt mv newtodo.txt todo.txt ...
Use a try/except, use with to open your files and just iterate over the file object f. You don't need a while loop to read a file. The iteration will stop when you reach the end of the file: with open('coffee.txt', 'r') as f: # closes automatically for qty in...
windows,batch-file,command-line,text-files
If the input file is large, this method should run faster because it does not check all the lines. It also correctly process lines with special Batch characters. @echo off setlocal EnableDelayedExpansion rem Read the first line, and create a dummy previous "endLine" with same name set /P "endName=" <...
c#,text-files,ienumerable,yield-return
this method yield returns all words, that start with a 'b' public static IEnumerable<string> ReadWords(this FileInfo fileInfo, Encoding enc) { using (var stream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read, FileShare.None)) { using (var reader = new StreamReader(stream)) { do { string[] line = reader.ReadLine().Split(' '); foreach (string word in line) {...
Using LINQ you can do: List<string[]> list = File.ReadLines("YourFile.txt") .Select(r => r.TrimEnd('#')) .Select(line => line.Split(',')) .ToList(); File.ReadLines would read the file line by line. .Select(r => r.TrimEnd('#')) would remove the # from end of the line .Select(line => line.Split(',')) would split the line on comma and return an array of...
java,text-files,java.util.scanner
Looks like you have a bug in the regex. * is the wildcard for 0 or more matches so ",|\\s*" will match the empty string. Try ",|\\s+".
So, turns out that the problem was nothing to do with either versions of my code. Apparently, I had some hidden characters in my Sublime text file that were throwing off the reading of the file. When I copied and pasted the contents of the original text file into a...
It's just because you forgot to strip the new line char at the end of each line. line = line.strip().lower() would help....
You may need to tweak the date field a bit. Simple parser: $aFile = file( 'infile.txt' ); $iCountLines = count( $aFile ); $aData = array(); for( $i = 0; $i < $iCountLines; ++$i ) { // Skip empty lines. if( empty( trim( $aFile[ $i ] ) ) ) { continue;...
c#,winforms,text-files,readfile
There are a couple of things you need to do. First, you need to create class level variables (more properly referred to as fields) to hold information that needs to be accessed by different methods. Secondly, you need to keep track of where you are (what line) in the file,...
try (Writer writer = Files.newBufferedWriter( Paths.get("filename.txt"), StandardCharsets.UTF_8, StandardOpenOption.WRITE, StandardOpenOption.APPEND)) { writer.write("something"); } The open options are a varargs list, and default to new file creation. BTW FileWriter uses the platform encoding, so you where right to not use that class. It is not portable....
python-3.x,printing,text-files,line
#!/usr/bin/env python3 import sys filename = sys.argv[1] # read the file line by line with open(filename) as f: for line in f: # split the line columns = line.split(",") # print all lines with "hello" as the first column if columns[0] == "hello": print(line, end='') ...
javascript,html,html5,text-files
Try this snippet, I just tried and it works :)! Live Demo (With Input File) var fileInput = document.getElementById('fileInput'); var fileDisplayArea = document.getElementById('fileDisplayArea'); fileInput.addEventListener('change', function(e) { var file = fileInput.files[0]; var textType = /text.*/; if (file.type.match(textType)) { var reader = new FileReader(); reader.onload = function(e) { var content = reader.result;...
c,text-files,infinite-loop,eof
EOF is not a character, you can't try to read it with fscanf(arq1, "%c", &eof); you should instead check fscanf()'s return value, which could be EOF or the number of matched arguments. Try with something like this int status; while ((status = fscanf(arq1, "%c", &aux)) != EOF) { . ....
vbscript,text-files,group-policy,gpo
Ok, so I tried it many different ways. If anyone is looking for an answer to do this, this is the way I've figured it out and the way I've decided to proceed. I will post all relevant code below. In Excel, the format of my table is as follows:...
The writer.writerow syntax you use corresponds to the csv module, which is used in the following way: import csv with open('some_file.csv', 'wb') as csvfile: writer = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL) writer.writerow(['Spam'] * 5 + ['Baked Beans']) writer.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam']) It seems to me you are using some...
python,python-3.x,encoding,character-encoding,text-files
Decode would only fail if the input contains characters outside the encoding mapping. If your file is purely ASCII, it will be read in exactly the same in both cases.
Rather than opening the file in Excel every time, you can create a new Excel file that uses the text file as a data source. When ever there is a change to the data, you can just right-clight and update, and everything else in the "parent" Excel file stays formatted...
Your code and posted desired result doesn't seem to be consistent so you probably have to adapt my code to your needs. But my code example will show you how to get rid of the DataTable and DataRow stuff. Instead LINQ methods are used where possible and a simple helper...
If there is no newline, one won't be generated. C tells you exactly what's there.
Not the most efficient implementation in the world, but you could do the following to get a random line from a file, if the file isn't too big, as described in this answer here: string[] lines = File.ReadAllLines(file_location); Random rand = new Random(); return lines[rand.Next(lines.Length)]; ...
python,sql-server,csv,text-files
You're writing only the last x,y,z,a assignments to the table. Try this: import csv import pymssql db = pymssql.connect(host='localhost', user='xx', password='xx', database='dbpython') cursor = db.cursor() filename = "ttest.txt" mynumbers = [] cursor.execute('truncate table tbl_contact') with open(filename, 'r') as f: for line in f: try: values = line.strip().split('|') x,y,z,a = int(values[0]),...
IMO, the best approach will be Read the whole line from file using fgets() Tokenize the input using "()" as delimiter. Check the token for non-NULL. use strtol() [or family] to convert the token to int or long int. Note; Always check for the success of fopen() before using the...
You're super close! You just have to move your for loop within the with block: with open('dna.txt', 'w+') as output: for _ in range(15): dna = random_dna_sequence(30) output.write(dna) ...
python,python-2.7,dictionary,replace,text-files
OK, let's take this step by step. main = open("INF108.txt", 'r+') words = main.read().split() main.close() Better to use the with statement here. Also, r is the default mode. Thus: with open("INF108.txt") as main: words = main.read().split() Using with will make main.close() get called automatically for you when this block ends;...
The ordering of version and config-register matter here. So you may be better off just iterating through the file twice. This way you can split up your sections of the file you need to find as groups. Once to find the values of version and once to find config-register. import...
Use the .GetFiles to list all files with specific search pattern : Dim pattern As string = "*" & FGY.Text & "*" For Each fi In GB.GetFiles(pattern) fi.Delete Next ...
vb.net,text-files,concatenation
Apologies it was a rookie error the text reader was corrupt i have just re installed it. Sorry if i have wasted your time.
You can achieve this in three ways: 1) as soon as the application starts get your filehandle and lock the file. This would of course only work if the applications runs (for example as a service) all the time 2) Adjust the priviledges in the files security tab and set...
f=open(file,"r") lines=f.readlines() result=[] for x in lines: result.append(x.split(' ')[1]) f.close() You can do the same using a list comprehension print [x.split(' ')[1] for x in open(file).readlines()] Docs on split() string.split(s[, sep[, maxsplit]]) Return a list of the words of the string s. If the optional second argument sep is absent...
you can replace your code with this.. this is a starting point, you can do many improvements to this code, but this will work. change REPOSITORY_FILE_PATH to your data file class InventoryOutput implements ActionListener { private final String REPOSITORY_FILE_PATH = "C:\\temp\\book-repo.txt"; private final File REPOSITORY_FILE = new File(REPOSITORY_FILE_PATH); public void...
I think you can find out answer in these links http://stackoverflow.com/questions/7706170/is-there-a-maximum-line-length-in-a-textfile-without-a-linebreak http://superuser.com/questions/431352/how-to-view-text-files-with-line-length-more-than-1024 http://stackoverflow.com/questions/1448500/is-there-a-line-length-limit-for-text-files-created-from-perl...
It isn't very clear what you are asking. If you want to load words from a text file you should look at using NSString's string parsing methods. The NSString method componentsSeparatedByString: will break a large string up into an array of pieces using the specified string as a delimiter. (You...
To read the text after the # characters you must read the file content up to the # characters first. Also, in PowerShell you normally read files either line by line (via Get-Content) or completely (via Get-Content -Raw). You can discard thos parts of the read content that don't interest...
java,text-files,java.util.scanner
Don't keep closing std input every time you call the getInput method. Scanner::close closes the underlying stream. Create the Scanner outside and keep using it. Create it somewhere where it lives till the last time you call getInput. Pass the Scanner object to the getInput method. Scanner sc = new...
InputMismatchException can be thrown because it is nether Integer either Double It is much better to read a part as a String and then decide When it is deciding, it throws NumberFormatException which can be catched In following code there are two writers separated as you wanted, It could looks...
Using awk: awk ' FNR==1{ #Header line: fn[++i]=FILENAME; # record filenames fn[0]=$0; # & file header } (FNR>1){ # For lines other than header lines list[$0]++; # Record line file_list[$0 FILENAME]++; # Record which file has that line } END{ for(t=0;t<=i;t++) printf "%s\t", fn[t]; # Print header & file names...
Firstly, /n is not a single character. \n is the newline character which you require. getline(myfile.line) is an invalid statement, as myfile, a , an object of ifstream, has no member line. Change it to: std::getline(myfile,line); ...
windows,batch-file,logging,cmd,text-files
The easiest way is to write to both places @echo off setlocal enableextensions enabledelayedexpansion (for /f "usebackq delims=" %%a in ("iplist.txt") do ( ping -n 1 "%%~a" >nul && set "msg=%%~a ok" || set "msg=%%~a failed to respond" >con echo(!msg! echo(!msg! )) > "logfile.txt" Pause You can see the first...
s = " I want to detect both March 20, 2013 and February 2013 3 and list them" import re print(re.findall(r"([A-Z][a-z\s\d]+, \d+|[A-Z][a-z\s]+\d+)",s)) ['March 20,2013', 'February 2013'] ...
You should parse and set accordingly. Create a QWidget, parse the first line of the text file, set its size. Then parse next lines to get the number of buttons, create widgets dynamically. Something like: // main // ... QString geoLine = stream.readLine(); int width = geoLine.split(" ")[1].toInt(); int height...
Your code calls LineNumberReader.readLine for every scanner token. Presuming a) each Scanner uses the default delimiter (in which case each line has 2 tokens) b) LineNumberReader.readLine increments the value returned by LineNumberReader.getLineNumber until the the file has been fully read - then for each token (rather than each line) it...
java,arrays,arraylist,text-files
The reason that it never loads the data from disk on first startup is because the first if statment in case 3 checks to see if PatientList.size is empty and if it is do not load data from disk (the else statment only runs if there is somthing in the...
python,type-conversion,text-files
money is a file object, not the content of the file. To get the content, you have to read the file. If the entire file contains just that one number, then read() is all you need. moneyx = float(money.read()) Otherwise you might want to use readline() to read a single...
Use a defaultdict and store values in a list: s="""Dave:23 Adam:12 Jack:13 Dave:25 Adam:34 """ from collections import defaultdict d = defaultdict(list) for line in s.splitlines(): name,val = line.split(":") d[name].append(int(val)) print(d) defaultdict(<class 'list'>, {'Jack': [13], 'Adam': [12, 34], 'Dave': [23, 25]}) So for your file just do the same: d...
string,function,variables,powershell,text-files
Have you tried: Add-Content $NewFilePath " `$TimeStart=Get-Date" Add-Content $NewFilePath " `$AccountName=""$($SubscriptionName)""" Escape characters, Delimiters and Quotes The PowerShell escape character is the grave-accent(`). The escape character can be used in three ways: When used at the end of a line, it is a continuation character - so the command will...
c,loops,pointers,linked-list,text-files
You need to set temp=temp->next before assigning temp->name and temp->id rather than after doing so otherwise you are overwriting the previous node's data.
javascript,ios,cordova,text-files,filewriter
Turns out there was nothing wrong with the code above, except that Apple forbids writing to app bundle after the bundle is installed. The bundle is signed and no modifications are allowed after that. To be able to write data, simply change cordova.file.applicationDirectory to cordova.file.dataDirectory and add the following to...
Quite obviously your code does not insert any data in positions 1, 3 and 4. The error message shows just commas and nothing in between. The offending statement in your code is this: INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) VALUES ($parts[0], $part[1], $parts[2], $part[3], $part[4]); Add a few s'es in part 1,...
Just do the division: while( reader >> id && reader >> howMany ){ //as long as you can read another pacient data int sum = 0; //sum accumulates the pressure readings per pacient double avg; cout << "The Patient ID Is: " << id << endl; cout << "The Number...