如何编写将输入文件和输出文件名作为输入的函数,读取输入文件并写入输出文件

时间:2019-10-22 04:41:46

标签: python-3.x file

我需要获取输入文件的内容,并将其添加到包含特定输入的每一行中,并且输出应说明输入所在的季节。

例如'cs'将输出为'cs Spring'

def aSeason(inputFile,outputFile):

with open(inputFile, 'r') as add:
    for lines in add:
        if lines == ['cs 101']:
            return line + ['Fall']

    if lines == ['cs 201']:
        return line + ['Spring']

with open(outputFile, 'w') as add:

1 个答案:

答案 0 :(得分:0)

读取和写入行的代码有时会很尴尬,因为您需要处理不可见的字符,例如换行符(\ n)(在Windows中为回车符(\ 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')