如何通过python打开文件

发布于 2021-01-29 19:34:08

我对编程和python语言非常陌生。

我知道如何在python中打开文件,但问题是如何将文件作为函数的参数打开?

例:

function(parameter)

这是我写出代码的方式:

def function(file):
    with open('file.txt', 'r') as f:
        contents = f.readlines()
    lines = []
    for line in f:
        lines.append(line)
    print(contents)
关注者
0
被浏览
89
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    您可以轻松地传递文件对象。

    with open('file.txt', 'r') as f: #open the file
        contents = function(f) #put the lines to a variable.
    

    然后在您的函数中,返回行列表

    def function(file):
        lines = []
        for line in f:
            lines.append(line)
        return lines
    

    另一个技巧是,python文件对象实际上具有读取文件行的​​方法。像这样:

    with open('file.txt', 'r') as f: #open the file
        contents = f.readlines() #put the lines to a variable (list).
    

    第二种方法,readlines就像您的功能一样。您不必再次调用它。

    更新 这里是您应该如何编写代码的方法:

    第一种方法:

    def function(file):
        lines = []
        for line in f:
            lines.append(line)
        return lines 
    with open('file.txt', 'r') as f: #open the file
        contents = function(f) #put the lines to a variable (list).
        print(contents)
    

    第二个:

    with open('file.txt', 'r') as f: #open the file
        contents = f.readlines() #put the lines to a variable (list).
        print(contents)
    

    希望这可以帮助!



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看