Reading and Displaying Data from a .Txt File

Reading and displaying data from a .txt file

BufferedReader in = new BufferedReader(new FileReader("<Filename>"));

Then, you can use in.readLine(); to read a single line at a time. To read until the end, write a while loop as such:

String line;
while((line = in.readLine()) != null)
{
System.out.println(line);
}
in.close();

Issue with reading data from a txt file

I do not see four spaces in your data files, but the error message is 'For input string: "0 0"'
I guess you have a tabulation in your file. You do not see it in your editor, but it might was converted to four spaces.
Try to replace your

split(" ");

to

split(""\\s+""); \\ Thanks for the comment, I did not think about several whitespace characters.

"\s+" will understand several spaces and the tabulations as well.
I hope this helps.

Reading value from a .txt file and writing it into output file

Okay, if I understand you correctly, you'd like to open several .txt files from a single directory and then concatenate their contents. I recommend using list.files (like you already are) and then lapply and readLines to open those files.

Get the locations of the .txt files. This produces a list with each element of the list being a directory (file location):

dirs <- list.file(path="path/to/input/directory", full.path=TRUE)

Use lapply to iterate over the elements of the list (like your for loop) and open them with the function readLines. This produces a list with the same number of elements as dirs, but this time it contains the contents of the text files:

myfiles <- lapply(dirs, readLines)

Finally, combine these elements of the list (each containing the contents of one text file) into one object, which you can save as a single text file.

dat <- do.call("rbind", myfiles) # note rbind might need to be replaced with "c" depending on the contents of the .txt files

Sorry if I am missing something or misunderstood. Please comment and I will adapt accordingly.

How to read data from txt file in python

Read the tutorials first.

  • if you are reading file defining a function isn't necessary.
  • learn basics first
  • if you are just reading file and you are a beginner in programming, you are taking a complicated approach.
  • take a simple approach and that helps you comprehend the input, output and ultimate goal.

Here is a quick tips for beginner and the simplest way of reading a file in python.

with open("phone_book.txt") as mytxt:
for line in mytxt:
print (line)

Or do something with line

# if you want to split the line
# assuming data is tab separated
newline = line.rstrip("\n").split("\t")

# if you want conditional printing
if len(line) > 0:
print(line)

Lessons:

  • when you with open ... file will auto close at the end when it comes out of that scope.
  • using for line with out doing .read() prevents you from loading all the data on the memory.
  • fix your indentation issues

reading data from a textfile and displaying it on the textview

Change to the following:

InputStream is = getResources().openRawResource(R.raw.temp);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
String entireFile = "";
try {
while((line = br.readLine()) != null) { // <--------- place readLine() inside loop
entireFile += (line + "\n"); // <---------- add each line to entireFile
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
text.setText(entireFile); // <------- assign entireFile to TextView
break;

How to read a txt file that contains different tables in it

You said text file and show a spreadsheet, so I'll demonstrate on a multi-table CSV file:

csvtext <- '[SETUP]
ExpName:
GroupName:
,,
Experiment,Group,Voltage
1,1,1
2,2,2
3,3,3
,,
[RESULT]
Group,Dev,V3
1,1,1
3,3,3
4,4,4
,,
[Data]
"mpg","cyl","disp"
21,6,160
21,6,160
22.8,4,108
'

Read it in as text:

# you may use something like
# rawtext <- readLines("path/to/file.csv")
rawtext <- readLines(textConnection(csvtext))
str(rawtext)
# chr [1:21] "[SETUP]" "ExpName:" "GroupName:" ",," "Experiment,Group,Voltage" "1,1,1" "2,2,2" "3,3,3" ",," "[RESULT]" ...

We can now split the data based on the "empty" lines, then drop these empty lines:

spltext <- split(rawtext, cumsum(!grepl("[^,\\s]", rawtext)))
spltext <- lapply(spltext, function(z) if (grepl("[^,\\s]", z[1])) z else z[-1])
str(spltext)
# List of 5
# $ 0: chr [1:3] "[SETUP]" "ExpName:" "GroupName:"
# $ 1: chr [1:4] "Experiment,Group,Voltage" "1,1,1" "2,2,2" "3,3,3"
# $ 2: chr [1:5] "[RESULT]" "Group,Dev,V3" "1,1,1" "3,3,3" ...
# $ 3: chr [1:5] "[Data]" "\"mpg\",\"cyl\",\"disp\"" "21,6,160" "21,6,160" ...
# $ 4: chr(0)

(Note that the $ 0 indicates that the name is "0" not 0, so we'll need to use string-numbers for indexing later.)

From here, since you only want the [Data] section, then

read.csv(text = spltext[["3"]][-1])
# mpg cyl disp
# 1 21.0 6 160
# 2 21.0 6 160
# 3 22.8 4 108

Reading from a .txt file and printing in a table form

You can do this:

headers = ["Resident Number", "Rent Date", "Customer number", "Rent ammount", "Ammount paid", "Outstanding Ammount"]

print(" ".join(headers))
for line in open("test.txt", "r"):
line = line.strip().split(",")
line.append(str(int(line[3]) - int(line[5])))
if line[5] == line[3] or line[4] in ("N", "P"):
continue
for i, word in enumerate(line):
if i == 4:
continue
print(word.ljust(len(headers[i - (i > 4)])), end=" " * ((i - (i > 4)) != len(headers) - 1))
print()

Output:

Resident Number    Rent Date    Customer number    Rent ammount    Ammount paid    Outstanding Ammount
R5 22/09/2015 C6 815 400 415
R8 23/09/2015 C9 370 200 170
R9 25/09/2015 C10 480 250 230


Related Topics



Leave a reply



Submit