2011-09-24 110 views
1

我有2個文件,我試圖拼湊一個擁有約300線和其他具有瑪貝85.文件蟒蛇循環文本

我想有85到循環文件,直到它增加了一個線文本到每個其他文件行。 這裏是我的代碼放在一起迄今爲止

name_file = open("names.txt", "r") 
year_file = open("years.txt", "r") 
for line in name_file: 
    print line.strip()+(year_file.readline()) 

下面是輸出的外觀,當它運行的數字像一些例子

LLOYD1999 

TOMMY2000 

LEON2001 

DEREK2002 

WARREN2003 

DARRELL2004 
JEROME 
FLOYD 
LEO 

我希望它輸出這樣

LLOYD1999 
LLOYD2000 
LLOYD2001 
LLOYD2002 
LLOYD2003 
LLOYD2004 

TOMMY1999 
TOMMY2000 
TOMMY2001 
TOMMY2002 
TOMMY2003 
TOMMY2004 
ect... 

回答

2
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)) 
0
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() 
+1

你在一個循環內打開years.txt(-1)? –

0
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 
2
# 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