how do I make python save each output without overwriting the file?


I am practicing website hacking and I have this script. I want it to save each finding in one file. It currently replaces what it found with the new finding.

import requests

def request(url):
        return requests.get("http://" + url)
    except requests.exceptions.ConnectionError:
    except requests.exceptions.InvalidURL:
    except requests.urllib3.exceptions.LocationParseError:

target_url = ""

with open("/home/kali/PycharmProjects/websitesub/common.txt", "r") as wordlist_file:
     for line in wordlist_file:
        word = line.strip()
        test_url = target_url + "/" + word
        response = request(test_url)
        if response:
            with open("/home/kali/PycharmProjects/websitesub/output.txt", "w") as f:
                f.write("DIR" + test_url)
                print("DIR" + test_url)
Asked By: Cezar



this should work

with open("data1.txt", "a", encoding="utf-8") as file:
    file.write(the thing you want to write)

you can define a new output filename every time you save the file
for example add the count of file in the directory

dir_path = r'homekalipycharmprojectswebsitesub'
count = len([entry for entry in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, entry))])
filename = f"output+{count}.txt"
output_file= os.path.join(dirpath, filename)

if response:
       with open(output_file, 'w') as f:
Answered By: Jed Ben nasr
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.