![](/img/trans.png)
[英]How could I use the list data type as a parameter in the 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.