Suppose pet_names.txt is the name of a text file in our current directory, and we successfully opened the file for reading by executing the following statement:
The function print_first_line takes one parameter, fname, the name of a text file. The function should open the file for reading, print the first line from the file, and close the file.
The function get_second_line takes one parameter, fname, the name of a text file. The function should open the file for reading, determine the secondline of the file, close the file, and return the second line (a string).
As the following for loop iterates through each line of the file, the loop variable (line) represents the current line of the file as a string of characters.
myFile = open("someTextFile.txt", "r")
for line in myFile:
do something on each iteration
do a second thing on each iteration
etc...
myFile.close()
PROBLEM: Read a string from standard input. Then, iterate over a text file called "cards.txt" and, for each line of the file that starts with the string read from standard input, print that line.
The function file_first_chars takes one parameter, fname, the name of a text file, and returnsa string made up of the first character from each line in the file.Β You may assume there are no blank lines in the file.
The function first_words takes one parameter, fname, the name of a text file, and returns a list containing the first word from each line of the file. For example, if the file contents are:
then the list ["apples", "bananas", "limes"] should be returned.NOTE: You may assume the file will contain no blank lines.BIG HINT: If lineis a string representing a line of text (inside of a for loop!), then L = line.split() creates a list of the words in the line.
The function print_last_line takes one parameter, fname, the name of a text file. The function should open the file for reading, read the lines of the file until it reaches the end, print out the last line in the file, report the number of lines contained in the file, and close the file.
The function last_wordstakes one parameter, fname, the name of a text file, and returns a list containing the last word from each line of the file. For example, if the file contents are:
The function print_line_if_exists takes two parameters, fname(a string, the name of a text file) and line_num (a non-negative integer, supposedly indexing a line in the file).