栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何通过python打开文件

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何通过python打开文件

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

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)

希望这可以帮助!



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/610407.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号