繁体   English   中英

如何通过python中的function参数打开文件?

[英]How could I open a file via the function parameter in python?

我正在尝试通过函数的参数打开文件。 我正在尝试实现的功能将是一种多用途的功能,可用于不同的文件。

def word_editor(open(filename, 'f'))

这是打开它的正确方法吗? filename名将代表我打开的任何文件。

定义任何函数时,您只应列出参数名称。 这就是为什么您的行def word_editor(open(filename, 'f'))不正确的原因。 如果要使用类似文件的对象,则应将其作为这样的参数传递:

def word_editor(fl):
    text = fl.read()
    print(text)

之后,您可以使用以下功能:

f1 = open("file1.txt", "r")
word_editor(f1)
f1.close()

with open("file2.txt", "r") as f2:
    word_editor(f2)

我想你想要这个。

def test(file_object):
     for line in file_object:
         print(line) 

test(open('test.txt','r'))

输出:

line #1
line #2
....  
....
line #n 

另外,您可以将filename作为函数的参数传递,如下所示:

def test(file_name):
    with open(file_name,'a+') as f:  
         # do whatever you want to do. 

test('your_file.txt')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM