您可以轻松地传递文件对象.
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)
希望这有帮助!