- Home /
The question is answered, right answer was accepted
Why do I get a length of 1 when getting data from a CSV file?
Why does the following script fail to get data from a CSV file? When I debug, it gives me a length of 1, whereas there are over forty lines in the CSV. When I attach the script to Unity, it skips every line past the "for" statement (I assume this is because it keeps reading the length as 1). I pasted the first few lines from the CSV after the script.
string[] data = scenarioInfoTextFile.text.Split(new char[] { '\n' });
Debug.Log(data.Length);
for (int i = 1; i < data.Length - 1; i++)
{
string[] row = data[i].Split(new char[] { ',' });
if (row[0] != "")
{
names q = new names();
q.sceneNumber = int.Parse(row[0]);
q.sceneYear = int.Parse(row[2]);
etc...
2,Tutorial,1939,9,0,19390900,Tutorial,1000,2000,3000,no
3,1939 – Wielun,1939,9,1,19390901,1939 – Wielun,2000,3000,5000,no
4,1939 – Piotrkow,1939,9,2,19390902,1939 – Piotrkow,2000,3000,5000,no
etc...
Answer by alexianphilosophy · Feb 04 at 05:46 PM
I think I see what you're trying to do with splitting by \n. I recently was working on something with a .tsv source and instead of splitting using text.Split, I used this https://docs.microsoft.com/en-us/dotnet/api/system.io.file.readalllines?view=net-6.0 File.ReadAllLines()
function to split my file's lines. It worked really well for me as I could then iterate through every line and split the line into an array of strings using the Split() function. Maybe try:
Debug.LogWarning($"Processing catalogue.csv...");
string[] lines = File.ReadAllLines($"{Application.dataPath}{csvPath}");
for (int l = 0; l < lines.Length; l++)
{
string[] splitData = lines[l].Split(',');
//Do something with the split data
}
Of course you have to input the csvPath, but it's just a file name. (e.g. catalogue.csv).
I get an error message (feature interpolated strings not avail on C# 4) on the brackets part of the line: string[] data = File.ReadAllLines($"{Application.dataPath}{scenarioInfoTextFile.csv}");
I am not sure why my original code is not working. I use the same exact code in other places and there are no issues there. This one too worked until the other day and I have no idea what I had done that created this problem and can't find a way to debug it. Actually - I did make a change to the CSV by adding a number of lines to it. But I don't see how this could have impacted the code so now it only reads one line.
I mean, what's the difference between this and the other locations in which you use the code? You should also try to just use the code snippet I pasted in.
No idea what the difference is - I just copied the code from script to script once I made it work the first time around. I tried to use your code snipped but could not make it work.
Follow this Question
Related Questions
ReadLine to a Variable 2 Answers
Add asset to array during runtime 0 Answers
csv to unity 0 Answers
Using an Excel generated .csv file 1 Answer