簡體   English   中英

在文件python中循環文本

[英]looping text in file python

我有2個文件我試圖放在一起一個有大約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...
# 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
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))
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()
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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM