简体   繁体   English

Python中具有多个参数的函数

[英]Function with multiple parameters in Python

I'm supposed to define a function that has 3 parameters, a path, a string and an integer.我应该定义一个具有 3 个参数、一个路径、一个字符串和一个整数的函数。 The path will describe the location of a file, and the string will be written into the file as many times as the integer.路径将描述文件的位置,字符串将被写入文件的次数与整数一样。

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

I've managed to write a path and print a string into that file, but I'm not able to use the integer parameter for my task.我设法写了一个路径并将一个字符串打印到该文件中,但我无法将整数参数用于我的任务。 Can someone please help out with an easy to understand explanation as well?有人可以帮忙提供一个易于理解的解释吗? Thanks!谢谢!

Is this what you want?这是你想要的吗?

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)

However, this won't truncate or overwrite the file.但是,这不会截断或覆盖文件。 If you want that too:如果你也想要:

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')

please find inline comments请查找内嵌评论

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