簡體   English   中英

Python中具有多個參數的函數

[英]Function with multiple parameters in Python

我應該定義一個具有 3 個參數、一個路徑、一個字符串和一個整數的函數。 路徑將描述文件的位置,字符串將被寫入文件的次數與整數一樣。

def param(path, x: str, y: int)
    string = open(path, "a")
    string.writelines(y + "\n")

我設法寫了一個路徑並將一個字符串打印到該文件中,但我無法將整數參數用於我的任務。 有人可以幫忙提供一個易於理解的解釋嗎? 謝謝!

這是你想要的嗎?

def write_lines(path,string,number):
    with open(path,"a+") as file:
        for i in range(number):
            file.write(string+"\n")
write_lines('logins.txt',"hello",5)

但是,這不會截斷或覆蓋文件。 如果你也想要:

def write_lines(path,string,number=1,truncate='yes'):
    with open(path,"a+") as file:
        if truncate.lower()=="yes":
            file.seek(0)
            file.truncate()
    
        for i in range(number):
            file.write(string+"\n")

write_lines('login.txt',"ello",5,'yes')

請查找內嵌評論

def param(path, x: str, y: int):
    with open(path, 'w') as f:
        f.writelines((x+'\n' for _ in range(y))) #(y+'\n' for _ in range(n)) is a generator expression
        # for memory efficiency

# calling the function       
param('sample.txt', 'hello', n)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM