How best to read a File into Liststring
var logFile = File.ReadAllLines(LOG_PATH);
var logList = new List<string>(logFile);
Since logFile
is an array, you can pass it to the List<T>
constructor. This eliminates unnecessary overhead when iterating over the array, or using other IO classes.
Actual constructor implementation:
public List(IEnumerable<T> collection)
{
...
ICollection<T> c = collection as ICollection<T>;
if( c != null) {
int count = c.Count;
if (count == 0)
{
_items = _emptyArray;
}
else {
_items = new T[count];
c.CopyTo(_items, 0);
_size = count;
}
}
...
}
Reading in .txt and using header string as list name
Since lists don't exactly have "names" (what you might confuse with reference), maybe you could use dictionaries:
my_list = [line.split() for line in open("file.txt", "r") ]
lists = {name: [] for name in my_List[0]} # my_List[0] = ['Name1','Name2']
for i in range(1,len(my_list)):
lists['Name1'].append(my_list[i][0])
lists['Name2'].append(my_list[i][1])
But in general try to avoid reading a whole file to a list (or a string). It is much more efficient to use iterators, where possible. Your case most definetly allows it:
with open("file.txt") as in_f:
first_line = in_f.readline().strip().split()
lists = {name: [] for name in first_line}
for line in in_f:
line_as_list = line.split()
lists['Name1'].append(line_as_list[0])
lists['Name2'].append(line_as_list[1])
If by name you mean reference to a list, as in create a variable with that name that points to a list you might use exec
:
with open("file.txt") as in_f:
first_line = in_f.readline().strip().split() # first_line = ['Name1','Name2']
for name in first_line:
exec(f"{name} = []")
for line in in_f:
line_as_list = line.split()
Name1.append(line_as_list[0])
Name2.append(line_as_list[1])
Read the docs about exec
How to write and read list to text file that contains user input using c#
You can use the static methods of the System.IO.File
class. Their advantage is that they open and close files automatically, thus reducing the task of writing and reading files to a single statement
File.WriteAllLines(yourFilePath, category);
You can read the lines back into a list with
category = new List(ReadLines(yourFilePath));
ReadLines
returns an IEnumerable<string>
that is accepted as data source in the constructor of the list.
or into an array with
string[] array = ReadAllLines(yourFilePath);
Your solution does not write anything to the output stream. You are initializing a TextWriter
but not using it. You would use it like
tw.WriteLine(someString);
Your code has some problems: You are declaring a category variable k
, but you never assign it a category. Your list is not of type category.
A better solution would work like this
var categories = new List<Category>(); // Create a categories list.
while (true) { // Loop as long as the user enters some category name.
Console.WriteLine("Enter name of category: ");
string s = Console.ReadLine(); // Read user entry.
if (String.IsNullOrWhiteSpace(s)) {
// No more entries - exit loop
break;
}
// Create a new category and assign it the entered name.
var category = new Category { name = s };
//TODO: Prompt the user for more properties of the category and assign them to the
// category.
// Add the category to the list.
categories.Add(category);
}
File.WriteAllLines(yourFilePath, categories.Select(c => c.name));
The Category
type should be class. See: When should I use a struct instead of a class?
Read and convert row in text file into list of string
The reason your code doesn't work is you are trying to use split
on a list, but it is meant to be used on a string. Therefore in your example you would use row2[0]
to access the first element of the list.
my_list = row2[0].split(" ")
Alternatively, if you have access to the numpy
library you can use loadtxt.
import numpy as np
f = np.loadtxt("data.txt", dtype=str, skiprows=1)
print (f)
# ['second_row_1' 'second_row_2' 'second_row_3']
The result of this is an array as opposed to a list. You could simply cast the array to a list if you require a list
print (list(f))
#['second_row_1', 'second_row_2', 'second_row_3']
Related Topics
Verifying That a String Contains Only Letters in C#
Linq .Any VS .Exists - What's the Difference
Convert.Changetype() Fails on Nullable Types
Hashing Passwords with Md5 or Sha-256 C#
Validation Error Style in Wpf, Similar to Silverlight
How to Get the Name of the Current Executable in C#
Admin Rights for a Single Method
How to Execute an Ssis Package from .Net
Is There an Alternative to Bastard Injection? (Aka Poor Man's Injection via Default Constructor)
Why Is Inserting Entities in Ef 4.1 So Slow Compared to Objectcontext
Pass Parameter to Eventhandler
Deleting Specific Rows from Datatable
Why We Need Thread.Memorybarrier()
Retrieving the Calling Method Name from Within a Method
How to Run Visual Studio Without Plugin and All Third Party Feature