我对编程和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就像你的函数.别再叫了.

Update

第一种方法:

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-3.x相关问答推荐

像计数不显示在html和想知道如果我的模型设置正确

如何将多个字典合并到一个列中,并为不同的行使用相同的键

Pandas 插入的速度太慢了.对于跟踪代码,什么是更快的替代方案?

Python中根据分组/ID对两个数据框进行映射,以更接近值的升序排列

一起使用数据类和枚举

如何通过 python 使用 auth no priv 获取 SNMPv3?

如何统计一个值连续出现的次数?

隐藏Cartopy中高纬度非矩形投影的右侧轴(纬度)标签

以不规则频率识别数据框日期时间列上缺失的日期,并用关联值填充它们

以编程方式映射 uniprot ID 时如何解决 400 客户端错误?

例外:使用 Pyinstaller 时找不到 PyQt5 插件目录,尽管 PyQt5 甚至没有被使用

从 Python2 到 Python3 的这种解包行为的变化是什么?

内部如何使用 Python 语法?

使用 Sublime Text 3 在 Python 3 中打印 UTF-8

pip install dryscrape 失败并显示错误:[Errno 2] 没有这样的文件或目录:'src/webkit_server'?

如何在 Selenium 和 Python 中使用类型查找元素

在 Ubuntu 上为 Python3 安装 mod_wsgi

Pruning in Keras

python判断一个方法是否被调用而不模拟它

在 Keras 中训练神经网络的零精度