Python Forum

Full Version: Saving the print result in a text file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi guys another day another issue.. So I have this code

from contextlib import suppress
from ipaddress import IPv6Address, ip_address
 
 
def make_ipv4_set(file_like):
    results = set()
 
    for line in map(str.strip, file_like):
 
        addr = None
        with suppress(ValueError):
            addr = ip_address(line)
 
        if isinstance(addr, IPv6Address):
            continue
 
        results.add(line)
 
    return results
 
 
with (
    open("ip1_file.txt") as ip1_file,
    open("ip2_file.txt") as ip2_file,
):
    ip1_set = make_ipv4_set(ip1_file)
    ip2_set = make_ipv4_set(ip2_file)
 
 
results = ip1_set - ip2_set
 
for ip in results:
    print(ip)
Which does the work like i expect it to but what I need is instead of it printing the output in a terminal I want to output the result in a text file. So can anyone help me with the code. Much appreciated thank you
There is a basic tutorial for files on the forum:
[Basic] Files
(Sep-24-2022, 04:26 PM)Yoriz Wrote: [ -> ]There is a basic tutorial for files on the forum:
[Basic] Files

Thanks but I am slow learner perhaps you can help me?
with open('ip_out.txt', 'w') as fp:
    for ip in results:
        print(ip)
        fp.write(ip)
another suggestion is to use pandas library under python
You can print into file (unpack, separate with newline and direct stream to file):

with open('ip_out.csv', 'w') as f:
    print(*results, sep='\n', file=f)
(Sep-25-2022, 10:52 AM)perfringo Wrote: [ -> ]You can print into file (unpack, separate with newline and direct stream to file):

with open('ip_out.csv', 'w') as f:
    print(*results, sep='\n', file=f)

where do I insert this line of code?
(Sep-25-2022, 06:05 PM)Calli Wrote: [ -> ]where do I insert this line of code?

You can use it after defining name results. Prior use will raise NameError.

If you are not interested in outputting to the screen (print) then you can replace two last lines of your code.
(Sep-25-2022, 06:05 PM)Calli Wrote: [ -> ]where do I insert this line of code?
You should learn to test out code when get solutions.
It's after results(you make a set) line 30 in your code.
Both mine and perfringo(a little fancier🎈) code dos the same.
# Make a test set
results = {'1.255.255.254', '2.255.255.254', '3.255.255.254'}

with open('ip_out.csv', 'w') as fp:
    print(*results, sep='\n', file=fp)

with open('ip_out1.csv', 'w') as fp:
    for ip in results:
        fp.write(f'{ip}\n')
In files,and Sets dos not have order.
Output:
2.255.255.254 3.255.255.254 1.255.255.254