Search code examples
pythonexporthostnametxt

python create txt file with hostname name


I have a py script which creates txt file with some name, but i need that it named it with hostname. for ex when it creates txt file from test1 hostname it gave name to this txt file test1.txt

this is script. how to change it?

def save_passwords(self):
    with open('test.txt','w',encoding='utf-8') as f:
        f.writelines(self.passwordList)

Solution

  • Your code would look like this:

    import socket
    
    def save_passwords(self):     
        hostname = socket.gethostname()
        with open(hostname + '.txt', 'w', encoding='utf-8') as f: 
            f.writelines(self.passwordList)