如何将结果导出到.txt

时间:2018-02-28 15:48:50

标签: python python-3.x export

我运行了以下代码,我希望将脚本的输出导出到.txt文件以供日后查看。我怎么能这样做?

import socket, threading


def TCP_connect(ip, port_number, delay, output):
    TCPsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    TCPsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    TCPsock.settimeout(delay)
try:
    TCPsock.connect((ip, port_number))
    output[port_number] = 'Listening'
except:
    output[port_number] = ''



def scan_ports(host_ip, delay):

    threads = []        # To run TCP_connect concurrently
    output = {}         # For printing purposes

# Spawning threads to scan ports
for i in range(10000):
    t = threading.Thread(target=TCP_connect, args=(host_ip, i, delay, output))
    threads.append(t)

# Starting threads
for i in range(10000):
    threads[i].start()

# Locking the script until all threads complete
for i in range(10000):
    threads[i].join()

# Printing listening ports from small to large
for i in range(10000):
    if output[i] == 'Listening':
        print(str(i) + ': ' + output[i])



def main():
host_ip = input("Enter host IP: ")
delay = int(input("How many seconds the socket is going to wait until timeout: "))
scan_ports(host_ip, delay)

if __name__ == "__main__":
    main()

print ("Thank you for scanning")

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

with open("your_desired_txt_filename", "a") as myFile:

然后,在您要写入文件的部分:

myFile.write(your_content) ## Indent this line with the suitable level of indentation (it will be at least one indentation level  deeper than the `with` clause