如何通过python打开文件

2024-04-26 07:19:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我对编程和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)    

Tags: 文件函数代码语言示例参数parameter编程
3条回答

Python允许在一个with中放置多个open()语句。你用逗号分隔它们。你的代码是:

def filter(txt, oldfile, newfile):
    '''\
    Read a list of names from a file line by line into an output file.
    If a line begins with a particular name, insert a string of text
    after the name before appending the line to the output file.
    '''

    with open(newfile, 'w') as outfile, open(oldfile, 'r', encoding='utf-8') as infile:
        for line in infile:
            if line.startswith(txt):
                line = line[0:len(txt)] + ' - Truly a great person!\n'
            outfile.write(line)

# input the name you want to check against
text = input('Please enter the name of a great person: ')    
letsgo = filter(text,'Spanish', 'Spanish2')

不,在函数的末尾加上显式的返回不会得到任何结果。您可以使用return提前退出,但在结束时使用了return,函数将在没有return的情况下退出。(当然,对于返回值的函数,可以使用return指定要返回的值。)

def fun(file):
    contents = None

    with open(file, 'r') as fp:
        contents = fp.readlines()

    ## if you want to eliminate all blank lines uncomment the next line
    #contents = [line for line in ''.join(contents).splitlines() if line]

    return contents

print fun('test_file.txt')

或者您甚至可以修改它,这样它也可以将file对象作为函数参数

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

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)

希望这有帮助!

相关问题 更多 >