Reputation: 278
I have 2 files i am trying to put together one has about 300 lines and the other has mabey 85.
I want to have the file with 85 to loop until it adds a line of text onto each of the other files lines. Here is my code i put together so far
name_file = open("names.txt", "r")
year_file = open("years.txt", "r")
for line in name_file:
print line.strip()+(year_file.readline())
Here are some examples of what the output looks like when it runs out of numbers
LLOYD1999
TOMMY2000
LEON2001
DEREK2002
WARREN2003
DARRELL2004
JEROME
FLOYD
LEO
I want it to output like this
LLOYD1999
LLOYD2000
LLOYD2001
LLOYD2002
LLOYD2003
LLOYD2004
TOMMY1999
TOMMY2000
TOMMY2001
TOMMY2002
TOMMY2003
TOMMY2004
ect...
Upvotes: 1
Views: 168
Reputation: 69031
with open('years.txt') as year:
years = [yr.strip() for yr in year]
with open('names.txt') as names:
for name in names:
name = name.strip()
for year in years:
print("%s%s" % (name, year))
Upvotes: 2
Reputation: 15788
# Get a list of all the years so we don't have to read the file repeatedly.
with open('years.txt', 'r') as year_file:
years = [year.strip() for year in year_file]
# Go through each entry in the names.
with open('names.txt', 'r') as name_file:
for name in name_file:
# Remove any extra whitespace (including the newline character at the
# end of the name).
name = name.strip()
# Add each year to the name to form a list.
nameandyears = [''.join((name, year)) for year in years]
# Print them out, each entry on a new line.
print '\n'.join(nameandyears)
# And add in a blank line after we're done with each name.
print
Upvotes: 2
Reputation: 2071
name_file = open("names.txt", "r")
year_file = open("years.txt", "r")
for line in name_file:
year = year_file.readline().strip()
if year == '': # EOF, Reopen and re read Line
year_file = open("years.txt", "r")
year = year_file.readline().strip()
print line.strip() + year
Upvotes: 0
Reputation: 93020
name_file = open("names.txt", "r")
for line in name_file:
year_file = open("years.txt", "r")
for year in year_file:
print line.strip()+year.strip()
year_file.close()
name_file.close()
Upvotes: 0