In: Computer Science
In this task, you will create a Python script in which you will practice reading files in Python and writing them to a new output file. Construct a text file called Py4_Task3_input.txt that has the following lines:
4
Sandwiches 04 July 2020
Pasta 31 October 2014
Hot Dogs 15 November 2005
Tacos 25 December 1986
The first line of the file represents the number of lines in the data file. Write a loop that reads in each additional line (one line at a time) and stores this line first as a string, then converts it to a list, before moving on to reading the next line. Hint: the string for the second line should be Independence Day 04 July 2021 whereas the list for the second line should be [‘Independence’, ‘Day’, ‘04’, ‘July’, ‘2021’].
Create a second looping structure that outputs each line as a string, then as a list, before moving on to the next line. Name your output file Py4_Task3_output.txt. Name your main program Py4_Task3_teamnumber.py
Python Program:
""" Python program that reads data from file and outputs to another file """
# List to hold each line
lines = []
# Initially set numLines to 0
numLines = 0
# Opening file for reading
with open("d:\\Python\\Py4_Task3_input.txt") as fp:
# Reading number of lines
numLines = int(fp.readline())
# Iterating over line by line
for i in range(numLines):
# Stripping new line
line = fp.readline().strip()
# Adding to list
lines.append(line)
# Opening output file
ofp = open("d:\\Python\\Py4_Task3_output.txt", "w")
# Iterating over line by line
for i in range(numLines):
# Writing to output file
print(lines[i] + " \t " + str(lines[i].split()))
ofp.write(lines[i] + " \t " + str(lines[i].split()) +
"\n")
# Closing output file
ofp.close()
_________________________________________________________________________________________
Code Screenshot:
__________________________________________________________________________________________
Sample Run: