PYTHON
population_file = open('populations.txt')
# 1. Define a variable called total_population, assign 0 to this
variable
for line in population_file.readlines():
# 2. Add line to the total_population, convert line to an int
first
# 3. Close the population_file using the close() method
total_population_file = open('total_population.txt', 'w')
# 4. Use the write() method to write the total_population to the
total_population_file. Convert total_population to a string
# 5. Close the total_population_file using the close() method
Require
1.Program creates a new file called total_population.txt
2.The file total_population.txt contains a single line representing the sum of all populations from the populations.txt file
Below is populations.txt file
49177 56540 80429 91923 53752 390113 49631 133570 192294 50789
The program is given below: that open populations.txt file, read populations from file convert line to int, add into total_population and write total_population to total_population.txt file.
#open populations file
population_file = open('populations.txt')
# 1. variable called total_population, assign 0 to this
variable
total_population=0
for line in population_file.readlines():
# 2. add line to the total_population, convert line to an int
first
total_population = total_population + int(line)
# 3. Close the population_file using the close() method
population_file.close()
total_population_file = open('total_population.txt', 'w')
# 4. Use the write() method to write the total_population to the
total_population_file.
#Convert total_population to a string
total_population_file.write(str(total_population))
# 5. Close the total_population_file using the close()
method
total_population_file.close()
The screenshot of code is given below:
populations.txt
49177
56540
80429
91923
53752
390113
49631
133570
192294
50789
(after execution of program ) total_population.txt
1148218
Get Answers For Free
Most questions answered within 1 hours.