0

I know A lot of people ask about that but I tried a lot of method and none of it work for me.

I'm writing random string generator using python but when I save it to text file it only contains the last line.

But in command line its print all lines.

This is my code.

import sys
import random

    
ch = 'ZXCVBNM<>?":LKJHGFDSAQWERTYUIOP{}|+_)(*&^%$#@!~zxcvbnm,./;lkjhgfdsapoiuytrewq`1234567890'

nop = input('How Many password do you want to create?')
nop = int(nop)

lop = input('Whats the length of passwords?')
lop = int(lop)

for p in range (nop):
    password = ''
    for l in range(lop):
       password += random.choice(ch)
    print(password)
    pwd = open("pwd.txt", "w")
    pwd.write(password)
    pwd.close()
martineau
  • 119,623
  • 25
  • 170
  • 301
YazOT
  • 13
  • 2
  • 5
  • 1
    Opening a file with `w` mode erases the existing contents. And you're doing that inside the loop, so each time through the loop, it erases all the previous contents. Move the `open()` to before the loop, and move the `close()` after. – John Gordon Feb 18 '21 at 23:58
  • Opening a file in write mode overwrites its data. Move the line `pwd = open("pwd.txt", "w")` outside of the nested loops, and close the file only when you're done. – Ori David Feb 18 '21 at 23:59
  • Also you'll probably want to to write a newline after each password, or else all the passwords will be joined together on one line. – John Gordon Feb 19 '21 at 00:01

2 Answers2

2

because you are opening the file for writing for each password. Put your open() before for p in range(nop) and put your close() after that loop has completed. (Outdent it.)

Chris Curvey
  • 9,738
  • 10
  • 48
  • 70
1

You're printing the password as part of the for loop, so the file is getting rewritten on every line.

You probably want this

for p in range (nop):
   password = ''
   for l in range(lop):
      password += random.choice(ch)
print(password)
pwd = open("pwd.txt", "w")
pwd.write(password)
pwd.close()
gl1tch
  • 26
  • 3