您可以轻松地传递文件对象。
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)
希望这有助于!
不太清楚。你想用它做什么?你想传递文件对象,内容还是什么?快点,否则你会陷入低谷。 – aIKid
哦我想读取文件 – user2891763
你的意思是你想传递文件内容,作为参数? – aIKid