【问题标题】:How to use a file as input/output of a function in python? [closed]如何使用文件作为python中函数的输入/输出? [关闭]
【发布时间】:2020-11-16 17:17:02
【问题描述】:

我参加了学习python的课程;在我的课程中,我必须做一个具有以下条件的项目:

  • 我必须使用老师准备的模板。
  • 所有代码都应该写在函数中
  • 它需要打开一个 CSV 文件并有一个文件 (txt/csv) 作为输出。

现在,我的问题是如何引用具有以下结构的文件:

def function (input_file_name, output_file_name):

请在下面找到一个示例和简单的代码:

import csv

def function(input_file):

    with open ('filename.csv') as input_file:

        reader = csv.reader(input_file_name)

        for row in reader:

            print(row)

但是我的终端没有输出!

我的错误是什么?

【问题讨论】:

标签: python python-3.x function csv file


【解决方案1】:

你的方法可能是这样的:

import csv


def somefunction(in_filepath, out_filepath):
    with open(in_filepath) as infile:
        with open(out_filepath, 'w') as outfile:
            reader = csv.reader(infile)
            writer = csv.writer(outfile)

            for row in reader:
                print('Do something with row')
                writer.writerow(row)

for 循环中添加您想要的任何处理。应该使用命名输入和输出文件的strPathlike 对象调用该函数。例如

somefunction("in.csv", "out.csv")

【讨论】:

    【解决方案2】:

    您可以为此使用内置的open() 函数,例如open(input_file),然后使用.readlines() 将所有行作为列表读取,使用while 循环使用.readline() 读取每一行,使用.read() 将所有行读取为字符串

    【讨论】:

    • 我可以编写一个没有我上面提到的那些限制的代码并且它有一个正确的输出;但是,我不知道如何编写代码来打开文件,其中文件是函数的输入
    【解决方案3】:

    从 CSV 文件读取是使用 reader 对象完成的。 CSV 文件使用 Python 的内置 open() 函数作为文本文件打开,该函数返回一个文件对象。然后将其传递给阅读器,由阅读器完成繁重的工作。

    import csv
    
    with open('employee_birthday.txt') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        else:
            print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
            line_count += 1
    print(f'Processed {line_count} lines.')
    

    您还可以使用 writer 对象和 .write_row() 方法写入 CSV 文件:

    import csv
    
    with open('employee_file.csv', mode='w') as employee_file:
    employee_writer = csv.writer(employee_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
    
    employee_writer.writerow(['John Smith', 'Accounting', 'November'])
    employee_writer.writerow(['Erica Meyers', 'IT', 'March'])
    

    【讨论】:

    • 感谢您的回答,但我不能在函数之外添加任何代码,困难的部分是。我不知道如何定义相应文件为其输入的函数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多