This is an enhanced version of the code in the answer of Leonid Shifrin. You can specify a starting and ending line number and a CSV/TSV type option for a text file with rows ending with a newline. Notice also the CharacterEncoding
option of ImportString
that allows to display correctly UTF characters.
ClearAll[impRows];
Options[impRows] = {type -> "CSV", start -> 0, end -> 1};
impRows[fname_String, OptionsPattern[]] := Module[
{result, ftype, startLine, endLine, strm, lines},
startLine = OptionValue[start]; endLine = OptionValue[end];
ftype = OptionValue[type];
(* Open the file stream *)
strm = OpenRead[fname];
(* Skip a number of lines in the file *)
Skip[strm, String, startLine];
(* Read each line terminated by a newline as a String *)
lines = ReadList[strm, "String", endLine - startLine];
(* Close the stream *)
Close[strm];
result = ImportString[
StringJoin[Riffle[lines, "\n"]],
ftype,
CharacterEncoding -> "UTF-8"]
]
I am planning to include this in my DBAPI project together with another extremely useful piece of code for counting lines that I found here. Corrections, ideas, or further enhancements are most welcome.