Help with code to write a file

This is a port scanner that I’m doing for my python class. I need to make this code write a file. I’ve tried I’m terrible, please help.

#This is the one

import threading
import socket
import sys
from datetime import datetime

open_ports = []

def validateIP(ip):
    start=0
    count=0
    flag=0
    for i in range(len(ip)):
        if(ip[i]=='.'):
            count+=1
            if(len(ip[start:i])==0 or int(ip[start:i])>255 or int(ip[start:i])<0):
                flag=1
                break
            else:
                start=i+1
    if(flag==1):
        print("Invalid IP")
    else:
        if(count==3 and len(ip[start:])!=0 and int(ip[start:])<=255 and int(ip[start:])>=0):
           print("Valid IP")
        else:
           print("Invalid Ip")

#Driver Program
print("Enter Ip address:" )
ip=input()
validateIP(ip)


def scan_ports(name, start_port, max_port):
    try:
        for port in range(start_port, max_port):
            if (port - 1) == max_port - 1:
                print(name, "is finishing its tasks")
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            socket.setdefaulttimeout(1)
            result = s.connect_ex((target_ip, port))  # returns an error indicator
            if result == 0:
                open_ports.append(port)
            s.close()
    except socket.gaierror:
        print("Hostname could not be resolved")
        sys.exit()
    except socket.error:
        print("Could not connect to server")
        sys.exit()

portfiles = open('ScanResults', "w")

if __name__ == '__main__':
    print("-" * 50)
    print("Port scanner 3.0")
    print("-" * 50)

    target_ip = input('Enter target ip: ')
    start_port = int(input('starting port: '))
    max_ports = int(input('ending port: '))
    threads_count = int(input('threads count: '))

    threads = []

    i = 0
    next_max = start_port
    min_port = start_port
    while i < threads_count:
        i += 1
        next_max += ((max_ports - start_port) // threads_count)
        if i == threads_count:
            next_max = max_ports
        print("Thread{} starts: {} ends: {}".format(i, min_port, next_max))
        threads.append(threading.Thread(target=scan_ports, args=("thread{}".format(i), min_port, next_max)))
        min_port = next_max

    print("-" * 50)
    print("Scanning for open ports in range {}-{} . . .".format(start_port, max_ports))
    print("Time started: " + str(datetime.now()))
    print("-" * 50)

    for var in threads:
        var.start()

    for var in threads:
        var.join()

    print("Done scanning")
    print("Time Ended: " + str(datetime.now()))


    if len(open_ports) == 0:
        print("no open ports found in range {}-{}".format(start_port, max_ports))
    else:
        print("-" * 50)
        print("open ports found: ")
        for port in open_ports:
            print(port)
        print("-" * 50)

input("Scan Complete . . .")

What have you tried so far?

really I just don’t know what to write. I need the output of the port scan to written to a file. The code is not in the program. I know its open = with() I just need to define the file and get the output in a file.

I’ve edited your code for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').