繁体   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