I need to read the first line of a file and then the subsequent lines I want read using a loop.
eg:
Read in first line
Do stuff with the data
foreach ($line in $remainingLines)
{
more stuff
}
I have a rather messy way to achieve this but there must be a better way.
A common task for a program is to read data from a file. To read from a text file in C, you will need to open a file stream using the fopen() function. Once a file stream has been opened, you can then read the file line by line using the fgets() function. Both the fopen() and fgets() functions are declared in stdio.
To read the first line of a file in Python, use the file. readline() function. The readline() is a built-in function that returns one line from the file. Open a file using open(filename, mode) as a file with mode “r” and call readline() function on that file object to get the first line of the file.
You can use readlines()[n:] to skip the first n line(s).
Assign the content of the file to two variables. The first one will hold the first line, and the second variable gets the rest. Then loop over $remainingLines.
$firstLine,$remainingLines = Get-Content foo.txt
$contents = gc .\myfile.txt
write-host $contents[0]
for ($i=1; $i -lt $contents.Length; $i++)
{
write-host $contents[$i]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With