我是编程和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)
答案 0 :(得分:10)
您可以轻松传递文件对象。
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)
希望这有帮助!
答案 1 :(得分:0)
Python允许将多个open()语句放在一个单独的。你可以用逗号分隔它们。那么你的代码就是:
def filter(txt, oldfile, newfile):
'''\
Read a list of names from a file line by line into an output file.
If a line begins with a particular name, insert a string of text
after the name before appending the line to the output file.
'''
with open(newfile, 'w') as outfile, open(oldfile, 'r', encoding='utf-8') as infile:
for line in infile:
if line.startswith(txt):
line = line[0:len(txt)] + ' - Truly a great person!\n'
outfile.write(line)
# input the name you want to check against
text = input('Please enter the name of a great person: ')
letsgo = filter(text,'Spanish', 'Spanish2')
不,你通过在函数结束时显式返回来获得任何东西。你可以使用return提前退出,但最后你已经退出,并且函数将在没有它的情况下退出。 (当然,对于返回值的函数,可以使用return指定要返回的值。)
答案 2 :(得分:0)
def fun(file):
contents = None
with open(file, 'r') as fp:
contents = fp.readlines()
## if you want to eliminate all blank lines uncomment the next line
#contents = [line for line in ''.join(contents).splitlines() if line]
return contents
print fun('test_file.txt')
或者您甚至可以修改它,这样一种方式也可以将文件对象作为函数争论
答案 3 :(得分:0)
这是一种更简单的打开文件的方法,而无需在Python 3.4中定义自己的函数:
var=open("A_blank_text_document_you_created","type_of_file")
var.write("what you want to write")
print (var.read()) #this outputs the file contents
var.close() #closing the file
以下是文件类型:
"r"
:只是为了阅读文件
"w"
:只是写一个文件
"r+"
:一种允许读取和写入文件的特殊类型
有关详细信息,请参阅this cheatsheet。
答案 4 :(得分:-2)
def main():
file=open("chirag.txt","r")
for n in file:
print (n.strip("t"))
file.close()
if __name__== "__main__":
main()
the other method is
with open("chirag.txt","r") as f:
for n in f:
print(n)