Menu
  • HOME
  • TAGS

C# overwrite first few lines of a text file [duplicate]

c#,text-files

Read and write the file in terms of lines: var allLines = File.ReadAllLines("MyFile"); allLines[0] = "2345"; File.WriteAllLines("MyFile", allLines); ...

Outputting items in two combined lists in descending numerical order?

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)) ... >>>...

Creating a python table from key/counters text file

python,parsing,text-files

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...

Split text file into several parts by character

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#...

Unique words save to text file as a word per line

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...

Shell script file, checks if text file is empty or not

shell,text-files

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:...

How to check if sub-folder text file exists

vb.net,text-files

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....

Cannot print the final data in a line

java,text,text-files

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...

Python program wont write all information to .txt but it will to the shell ANSWERED

python,text-files

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...

Error writing text into a .txt file in python

python-3.x,text-files

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...

Android: display sentence from text file stored in res/raw folder

android,text-files

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...

Create a text file table with java with padding

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 Append From Text file outputs error

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.

Unix one-liner to swap/transpose two lines in multiple text files?

bash,unix,awk,sed,text-files

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....

Select specific data in text file to import in 2d array in c++

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;...

If I have three different text file how do I read them then sort them by average?

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...

TypeError: argument of type 'int' is not iterable? What does it mean?

python,list,text-files

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...

Plotting a string of numbers from text file

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...

How to generate text files and download a zip file in Javascript?

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....

How to get data's from text file in c#

c#,.net,text-files

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 - Need to make a cell array from a text column file

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 editting text file and saving strings to sharedpreferences

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...

How to print the content of multiple text files with one click

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...

Retrieving a value from a text file

android,text-files,storage

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...

Bash formatting text file into columns

arrays,bash,shell,text-files

Try the column command like column -t -s',' This is what I can get quickly. See the man page for details....

Extracting columns containing a certain name

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....

Reading tab (\t) separated text from file in shell

bash,shell,text-files

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[@]}....

How can i get the last integer saved to a textfile and display it i a TextView in Android?

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(); ...

I get an error with trying to parse the integer from the textfile [closed]

c#,text-files,system.io.file

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...

Read graphs from file as fast as possible

c,input,graph,text-files

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...

PHP: Filtering and posting a text file

php,csv,text-files,filtering

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:...

How do to I read in data from a text file which is carriage return line feed delimited to matlab?

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....

How to get certain information out of arraylist grouped into other lists in Java

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,...

Reading multiple text files into an array in C

c,arrays,text-files

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,...

grep: Invalid regular expression

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...

How to extract specific lines from a huge data file?

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...

Calling a function within fprintf syntax in C language

c,function,text-files

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...

Python- creating a text file with a variable as a name

python,text-files,filenames

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....

How to search for a sentence +1 in a file?

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...

Reading text file and skipping blank lines in vb.net

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...

display the text file item from certain column in jcombobox

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)); } } ...

How to read 2nd level sub-directory text file in vb.net

vb.net,text-files

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") ...

Need to update a text file with new content found in an other text file

bash,shell,text-files

You could use output redirection cat newtodo.txt > todo.txt <br> or You could rename newtodo.txt mv newtodo.txt todo.txt ...

Could not convert string to float - Reading from the fil

python,text-files

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...

Split a text file if two consecutive lines almost identical

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=" <...

Getting words out of a text file with C#

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) {...

read all lines in text file with separator

c#,text-files,readline

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...

Trouble constructing an object with data in a text file using commas as delimiters

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+".

Trouble with reading a subsection of a text file using comparison operators and string compare function

c++,text-files

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...

How to find a specific string in a .txt file Python

python,text-files

It's just because you forgot to strip the new line char at the end of each line. line = line.strip().lower() would help....

Text file data importing to php

php,import,text-files

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;...

Read Same Text File in Different Methods

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,...

How to write to a file without deleting privious existing data [duplicate]

java,file-io,text-files

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....

How to print select lines of a text file in python?

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='') ...

Reading a text file using Javascript

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 code to read a text file does not find EOF (end of file)

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) { . ....

Populate GPO from Text File using VBScript or other

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:...

Rewriting my scores text file to make sure it only has the Last 4 scores (python)

python,dictionary,text-files

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...

Why does opening a file in two different encodings work as expected?

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.

Column width goes back to orignal when importing .txt files EXCEL 2013

excel,text-files

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...

Sorting a DataTable by columns in a file

c#,arrays,linq,csv,text-files

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...

Count lines in ASCII file using C

c,ascii,text-files

If there is no newline, one won't be generated. C tells you exactly what's there.

How to randomize the text in a label

c#,random,label,text-files

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)]; ...

Only the last row is inserted to my sql database from a text file after splitting it with PYTHON

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]),...

Reading from a textfile in a certain format

c,text-files,filestream

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...

Write multiple prints in a text file

python,text-files

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: replacing multiple words in a text file from a dictionary

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;...

Save one part of a text file

python,python-3.x,text-files

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...

How to search and delete multiple text files from a directory using code

vb.net,text-files,vb.net-2010

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 txt text file merge / concatenate all files

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.

Preventing a user from deleting, modifying, ext

c#,text-files

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...

Reading specific columns from a text file in python

python,list,text-files

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...

Searching for specific text in a text file. Returning it to a textbox

java,search,text-files,jgrasp

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...

Large text file and characters Limitation problems in a line

database,data,text-files

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...

Using a text file as a set of values swift [duplicate]

ios,swift,set,text-files

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...

Powershell Reading text file

powershell,text,text-files

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...

NoSuchElementException: No Line Found, while reading in text file

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...

Java text file remove doubles from four column text file

java,io,text-files

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...

How can I get common rows that exist in at lest two files or more?

bash,text,text-files

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...

What did I do wrong in OOP in C++

c++,oop,text-files

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); ...

Output Batch File Results to Text File AND to the screen itself

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...

Detect the dates from text in text file. And then list them out using python

python,date,text-files

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'] ...

How to create or modify a QT form (after compilation) based on a text file

c++,windows,qt,text-files

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...

Writing a “\t” to a text file creates a line?

java,text-files,line-numbers

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...

Store patient information into text file and load it afterwards

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...

Float must be a string or a number?

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...

Reading data separated by colon per line in Python

python,text-files

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...

Combination into a file done in powershell (String + Variable)

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...

Linked List Loop Iterations alter global variable head

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 and Cordova/Phonegap FileWriter gives Invalid_Modification_Error on a simple text file write

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...

Saving data from textfile to PostGreSQL database using php

php,postgresql,text-files

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,...

How do I pull out the data file to find Average? Logic Help C++

c++,logic,text-files

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...