在文件python中循环文本

时间:2011-09-24 21:41:11

标签: python

我有两个文件,我试图放在一起,一个有大约300行,另一个有mabey 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...

4 个答案:

答案 0 :(得分: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

答案 1 :(得分: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))

答案 2 :(得分: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()

答案 3 :(得分: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