код для чтения и записи строк иногда неудобен, так как вам нужно позаботиться о невидимых символах, таких как символ новой строки (\ n) (а в окнах возврат каретки (\ r))
infile='intest.txt'
## contains:
#cs 121
#cs 122
#cs 166
#cs 260
#cs 999
outfile='tests.txt'
with open(infile, 'r') as inf:
with open(outfile, 'w') as outf:
# iterate over infile lines
for line in inf:
# strip whitespace and newline from line read in
sline = line.strip()
# check if it matches some predetermined line
if sline in ['cs 121','cs 215','cs 223','cs 260']:
outf.writelines(sline+' Fall\n')
elif sline in ['cs 122', 'cs 166', 'cs 224', 'cs 251', 'cs 261']:
outf.writelines(sline + ' Spring\n')
else:
outf.writelines(sline+'\n') # maybe doesn't match, keep line I guess
Вызвать это как функцию легко
def append_season(infile,outfile):
with open(infile, 'r') as inf:
with open(outfile, 'w') as outf:
# iterate over infile lines
for line in inf:
# strip whitespace and newline from line read in
sline = line.strip()
# check if it matches some predetermined line
if sline in ['cs 121','cs 215','cs 223','cs 260']:
outf.writelines(sline+' Fall\n')
elif sline in ['cs 122', 'cs 166', 'cs 224', 'cs 251', 'cs 261']:
outf.writelines(sline + ' Spring\n')
else:
outf.writelines(sline+'\n') # maybe doesn't match, keep line I guess
# call the function:
append_season(infile='intest.txt', outfile='tests.txt')