- Home /
Read random line of external text file data into a variable (JS)
So, what I want to do is this: Read data from a file "data.txt". I want to then pick a random line of that data, say line 3. At the moment, I'm reading the whole file. Can I just read line 3 of that file?
var fileName = "data.txt";
// read from filename
var sr = new StreamReader(Application.dataPath + "/" + fileName);
var fileContents = sr.ReadToEnd();
sr.Close();
// put data from filename into a variable
// var mydata = fileContents.Split("\n"[0]);
var mydata = fileContents;
// pick a random number between 1 and 10
var myrandom = Random.Range(1,10);
// I know this bit isn't right, but what I want is print (line myrandom of mydata);
It's in Javascript as that's more human-readable for me. I just can't get my head around C. Also, sorry I'm really new to all of this. I don't even know how to use tags on this website to show quoted code! :( Please help!!
All the answers you are going to get here involve reading all or part of the file, even if they return only the line you want. That's because there is no way to skip to line X in a text file without finding where all previous lines end first.
If you don't $$anonymous$$d that, then there is no problem with any of the answers you already got.
But if you really want a solution that doesn't scan the whole file in order to return a single line (for example, because doing so is extremelly slow, or you plan to read lines many times per second), you will need to request that clearly, because it would need a more efficient yet more complex solution.
Depending on your needs, my method could be more effective than ReadAllLines
if you don't have a huge number of lines. Otherwise go with @EvilWarren's solution.
Answer by EvilWarren · Oct 29, 2013 at 10:04 AM
Almost there, but you commented out a line you really needed
import System.IO;
var fileName = "data.txt";
function Start () {
// read from filename
var sr = new StreamReader(Application.dataPath + "/" + fileName);
var fileContents = sr.ReadToEnd();
sr.Close();
// put data from filename into a variable
var mydata = fileContents.Split("\n"[0]);
// pick a random number between 1 and 10
var myrandom = Random.Range(1,10);
print(mydata[myrandom]);
}
Important to make sure you have import System.IO there as well. Also, its convention to start indexing arrays at 0 so you might want to change the Random.Range to between 0 and 9.
Just to be safe:
var myRandom = Random.Range(0, myData.Length);
Good point, and you beat my slow fingers to an answer as well.
Small Q: When I'm doing an "import" or "using", formatting gets messed up. What you doing to keep it intact?
Try taking an extra new line before your code sample. The code formatting doesn't seem very reliable so I treat it like a rabid dog and give extra space.
Thank you all for your answers. I've gone with EvilWarren's answer (as this was easiest for me to understand). I'm sure vexe's answer is correct too, and I like the idea of just reading a single line. I can't understand yet how to pass functions to scripts or whatever and where they need to go, what they need to be attached to and what files to make, so I've just gone with the simpler answer provided by EvilWarren. Thank you all though for your responses :)
@tperry1x Comment pasted here. It disappeared into the ether due to -1 Answers Bug
Answer by vexe · Oct 29, 2013 at 10:02 AM
This does the job, quite good. It's tested. (Excuse my poor JS) - Just give it the file path, and the line number that you want. This does it without reading the whole file contents, and then picking up your line. I also wrote a GetNumberOfLines
for convenience. Don't forget to include System.IO;
NOTE: if you want the first line of your file, you pass it a 0, for nLine, second, 1, etc - Just like indexing an array.
[C#]
string ReadLine(string path, int nLine)
{
string line = "";
using (var reader = new StreamReader(File.Open(path, FileMode.Open))) {
int n = 0;
while (n++ <= nLine)
line = reader.ReadLine();
}
return line;
}
int GetNumberOfLines(string path)
{
int nLines = 0;
using (var reader = new StreamReader(File.Open(path, FileMode.Open))) {
nLines = reader.ReadToEnd().Split('\n').Length;
}
return nLines;
}
[JS]
function ReadLine(path : String, nLine : int) : String
{
var reader = new StreamReader(File.Open(path, FileMode.Open));
var line : String = "";
int n = 0;
while (n++ <= nLine)
line = reader.ReadLine();
reader.Close();
return line;
}
function GetNumberOfLines(path : String) : int
{
var reader = new StreamReader(File.Open(path, FileMode.Open));
var nLines = reader.ReadToEnd().Split("\n"[0]).Length;
reader.Close();
return nLines;
}
Test #1: Reads all the file, line by line
var path = @"somewhere";
var nLines = GetNumberOfLines(path);
for (var i = 0; i < nLines; i++) {
print (ReadLine(path, i));
}
Test #2: Reads a random line in the file
var path = @"somewhere";
var nLines = GetNumberOfLines(path);
var rand = Random.Range(0, nLines);
var randomLine = ReadLine(path, rand);
print (randomLine);
Answer by dallasbrands · Nov 07, 2013 at 01:10 AM
I think I'm getting this, but I'm not sure how to use EvilWarren's example to post the random line of data somewhere else. Does anyone have any ideas? (I'm trying to get it to post onto a different PHP page.
That is a totally unrelated question. Reading a file for a particular line has nothing to do with what will you do later with the data you just read.
Create a new question.
Your answer
Follow this Question
Related Questions
Help with XML reading and writing 1 Answer
Apply force from specific location in space 0 Answers
movement 2d in a grid 3 Answers
How do I acces a specific GameObject within the terrain???? 1 Answer