python - 如何通过python打开一个文件

标签 python function python-3.x

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

最佳答案

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

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)

希望这对您有所帮助!

关于python - 如何通过python打开一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19508703/

相关文章:

c++ - 如何将 3D 数组作为参数传递给函数 C++?还需要将全局变量传递给函数吗?

python - 如何在导入 python 模块时排除对象

python-3.x - 为什么在数据帧上调用 sum() 会生成错误的数字?

python - 检索 numpy 数组中具有特定值的随机项的索引

python - NumPy 中不一致的高级索引

Python - 使用 WConio 将 unicode 打印到控制台窗口

c++ - 两个数组是否相等函数c++

python - 测试列表修改是否是周期性的

C++ typedef 重命名函数

python - 在 Django 中获取早于 10 天的数据库表数据