如何通过python打开文件

use*_*763 14 python function python-3.x

我是编程和python语言的新手.

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

例:

function(parameter)
Run Code Online (Sandbox Code Playgroud)

这是我写出代码的方式:

def function(file):
    with open('file.txt', 'r') as f:
        contents = f.readlines()
    lines = []
    for line in f:
        lines.append(line)
    print(contents)    
Run Code Online (Sandbox Code Playgroud)

aIK*_*Kid 14

您可以轻松传递文件对象.

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

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

def function(file):
    lines = []
    for line in f:
        lines.append(line)
    return lines 
Run Code Online (Sandbox Code Playgroud)

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

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

使用第二种方法,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)
Run Code Online (Sandbox Code Playgroud)

第二个:

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

希望这可以帮助!

  • 首先定义函数,然后执行`with`语句. (2认同)