In: Computer Science
IN PYTHON
File Data --- In file1.txt add the following numbers, each on its own line (20, 30, 40, 50, 60). Do not add data to file2.txt.
Write a program. Create a new .py file that reads in the data from file1 and adds all together. Then output the sum to file2.txt. Add your name to the first line in file2.txt (see sample output)
Sample Output
Your Name
200
use a main function.
Python code:
def main():
#opening the file file1.txt
f=open("file1.txt","r")
#reading the values
lis1=f.readlines()
#closing file
f.close()
#converting the list to integers
lis1=list(map(int,lis1))
#opening the file file2.txt
f=open("file2.txt","w")
#write your name here
f.write("Your Name\n")
#writing sum to file2
f.write(str(sum(lis1)))
#closing file
f.close()
if __name__ == "__main__":
main()
Screenshot:
file1.txt:
file2.txt: