Python Forum
Writing to .txt file - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Writing to .txt file (/thread-25184.html)



Writing to .txt file - julio2000 - Mar-22-2020

Hi,
How do I write a piece of text like this into a .txt file?:

Jan:Kees:Piet:klaas
Kees:Kees:Piet:klaas
Klaas:Kees:Piet:klaas
Piet:Kees:Piet:klaas
Kees:Kees:Piet:klaas
Jan:jan:Piet:klaas
Jan:Kees:piet:klaas
Jan:henk:Piet:klaas
Jan:Kees:Piet:klaas

my current code looks like this:
proxies = input('proxies: ')
with open('Proxies.txt', 'r+') as file:
    file.write(proxies)
my input for proxies will be that list i've shown above. But when I run this code it doesn't write anything down in the file. Does somebody know how to do this?


RE: Writing to .txt file - SheeppOSU - Mar-22-2020

You're missing a comma on line 2 between "Proxies.txt" and "r+"


RE: Writing to .txt file - julio2000 - Mar-22-2020

yeah found that out earlier on, but still doesnt work


RE: Writing to .txt file - snippsat - Mar-23-2020

Need loop to write that,add new line(\n) when write to file and way to quit.
with open('Proxies.txt', 'a') as f:
    while True:
        proxies = proxies = input('proxies,<q> to quit: ')
        if proxies == 'q':
            break
        else:
            print(proxies)
            f.write(f'{proxies}\n')



RE: Writing to .txt file - julio2000 - Mar-23-2020

i want it to be able to write everything in once, not line by line


RE: Writing to .txt file - snippsat - Mar-23-2020

Can do that and can eg use white space as delimiter.
with open('Proxies.txt', 'a') as f:
    prox_text = ""
    proxies = input('proxies: ')
    prox_text += proxies
    prox_text = prox_text.split()
    f.write("\n".join(prox_text))
Test:
Output:
E:\div_code λ python pro_all.py proxies: Jan:Kees:Piet:klaas Jan:Kees:Piet:klaas Jan:Kees:Piet:klaas E:\div_code λ cat Proxies.txt Jan:Kees:Piet:klaas Jan:Kees:Piet:klaas Jan:Kees:Piet:klaas