PYTHON- I need help figuring out how you would read a file into a list THEN what
ID: 3800639 • Letter: P
Question
PYTHON- I need help figuring out how you would read a file into a list THEN what code you would use to find outt, for example, how many people were born in a specific year, writing the answer out into a file.
For instance
1. How many girl babies have been born since 1910?
2. How many boy babies have been born since 1910?
3. How many girl babies were born 1910? In 2012?
4. How many boy babies were born in 1910? In 2012?
5. What are the total number of babies born in Texas in 2012?
6. What are the total number of babies born in Texas with your name since 1910?
7. What are the total number of babies born in Texas with your name between 1910 and 1960? If you have a very uncommon name, feel free to pick any name that you might be curious about.
8. What name was the most popular (had the highest count in one year): * For males * For females
9. What name was that? * For males * For females
10. What year was that? * For males * For females
11. In what year was your name the most popular (had the highest count)?
Explanation / Answer
Ans: To read a file into list the following code can be used
text_file = open("filename.txt", "r") # give your file name, opens the file
lines = text_file.readlines() # read all the lines in file
print lines
print len(lines)
text_file.close()
You can also use ( lines = text_file.read().split(',') ) to make seperate or individual items
Answer for your second task
Follow the code to print how many people born in specific year.
def check():
datafile = file('example.txt') #your filename
found = False
for line in datafile:
if 1910 in line: # search for year you want
found = True # if year found
break
return found
found = check()
if found:
print lines #print the complete line which is output of
else:
print "not found the year"
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.