【问题标题】:How do I write a function that takes as input an input file and an output file name, reads the input file and writes to the output file如何编写一个函数,将输入文件和输出文件名作为输入,读取输入文件并写入输出文件
【发布时间】:2019-10-22 04:41:46
【问题描述】:

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

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

定义一个季节(输入文件,输出文件):

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:

【问题讨论】:

  • 你明白return是做什么的吗?
  • 老实说不是 100%。你能解释一下这种情况吗?

标签: python-3.x file


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2018-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-18
    • 2016-07-13
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多