0

i give you an example i click on run write a number in the console(how many keys) and then i get this random letters and numbers: 61PYY-ZEPY1-2H82R-V1JZ1-9VEF7, but i want that they are in my demofile2.txt. when i paste this in the write: '-'.join(''.join(random.choice(seq) for _ in range(5)) for _ in range(5)) it says seq is not definied

This is the code :

import random, sys

class KeyGen():
    def __init__(self):
        global i
        i = int(input("How many serial codes are you looking for? \n"))
        print("")
        self.main(i)

    def main(self, count):
        """ Our main iteration function, using simple
        capital letters, along with the numbers 0-9 """
        seq = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"

        for i in range(count):
            print('-'.join(''.join(random.choice(seq) for _ in range(5)) for _ in range(5)))

        print("\nCreated {} serial keys.".format(count))

if __name__ == '__main__':
    app = KeyGen()

text_file = open("demofile2.txt.")
text_file.write(THISISWHATISEARCH)
text_file.close()
IDONTCODE
  • 7
  • 4
  • 1
    Does this answer your question? [Print string to text file](https://stackoverflow.com/questions/5214578/print-string-to-text-file) – Tomerikoo Feb 11 '21 at 18:53
  • i know how to open the files and write in to them but idont know what are the Key codes – IDONTCODE Feb 11 '21 at 19:04
  • 2
    Your question says: *"i dont know how to write in to a .txt file over python"* and now you say you do. Your question is not clear to me then. I don't see any attempt to open a file or write to it in the code – Tomerikoo Feb 11 '21 at 19:05
  • text_file = open("demofile2.txt.") text_file.write(this part is what i search here should be the keys) text_file.close() – IDONTCODE Feb 11 '21 at 19:10
  • Replace `print` with `text_file.write`....? – Tomerikoo Feb 11 '21 at 19:11
  • but i want it too in the console – IDONTCODE Feb 11 '21 at 19:13
  • So add `text_file.write(whatever_you_print + '\n')`........... – Tomerikoo Feb 11 '21 at 19:13
  • Does this answer your question? [How to save python screen output to a text file](https://stackoverflow.com/questions/25023233/how-to-save-python-screen-output-to-a-text-file) – Tomerikoo Feb 11 '21 at 19:14
  • sry if i am stupid but what is whatever_you_print? – IDONTCODE Feb 11 '21 at 19:20
  • You're not stupid. It's just hard to understand with what exactly you struggle without a clear question and a [mre] – Tomerikoo Feb 11 '21 at 19:21
  • If you `print("\nCreated {} serial keys.".format(count))` and you want that in the file then just add `text_file.write("\nCreated {} serial keys.\n".format(count))` – Tomerikoo Feb 11 '21 at 19:22
  • NameError: name 'count' is not defined :( – IDONTCODE Feb 11 '21 at 19:25
  • It needs to be inside the `main` function yes? Please make an honest attempt to try and write to the file based on the links I provided you. Then [edit] your question with what exactly you're struggling with and a [mre] of your code. For example, for a good [mre], it is not even relevant that you're generating keys – Tomerikoo Feb 11 '21 at 19:27
  • i give you an example i click on run write a number in the console(how many keys) and then i get this random letters and numbers: 61PYY-ZEPY1-2H82R-V1JZ1-9VEF7, but i want that they are in my demofile2.txt. when i paste this in the write: '-'.join(''.join(random.choice(seq) for _ in range(5)) for _ in range(5)) it says seq is not definied – IDONTCODE Feb 11 '21 at 19:32
  • like this: NameError: name 'seq' is not defined – IDONTCODE Feb 11 '21 at 19:34
  • This became to hard to communicate. Please see the answer I posted. Hopefully that will explain it better – Tomerikoo Feb 11 '21 at 19:36

1 Answers1

0

In order to write to a file you simply need to pass a string to file.write(). In your case the same string you're printing.

One difference is that print automatically adds a new line at the end of each string (because of the default value of the argument end='\n'). So when writing to the file you can add an ending new-line. Alternatively, you can use print's file argument to avoid any change at all!

Now you just need to have the file descriptor available at the point where you want to write to it. That might depend on the design of the rest of your code, for simplicity of the example I will simply move it to the main function.

One more thing is when read/write-ing files, it is better to use the with context manager:

import random, sys

class KeyGen():
    def __init__(self):
        global i
        i = int(input("How many serial codes are you looking for? \n"))
        print("")
        self.main(i)

    def main(self, count):
        """ Our main iteration function, using simple
        capital letters, along with the numbers 0-9 """
        seq = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"

        with open("demofile2.txt.", 'w') as text_file:
            for i in range(count):
                print('-'.join(''.join(random.choice(seq) for _ in range(5)) for _ in range(5)), file=text_file)
                # text_file.write('-'.join(''.join(random.choice(seq) for _ in range(5)) for _ in range(5)) + '\n')

            print("\nCreated {} serial keys.".format(count), file=text_file)
            # text_file.write("\nCreated {} serial keys.\n".format(count))

if __name__ == '__main__':
    app = KeyGen()

I will use this chance for a general tip:

In Python there is no need to over-use classes. Maybe you come from a Java background where everything is classes, but here your class only serves as a gate-way to a function. So your code could be:

import random, sys

def main():
    """ 
    Our main iteration function, using simple
    capital letters, along with the numbers 0-9 
    """
    seq = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"

    count = int(input("How many serial codes are you looking for? \n"))
    with open("demofile2.txt.", 'w') as text_file:
        for _ in range(count):
            print('-'.join(''.join(random.choice(seq) for _ in range(5)) for _ in range(5)), file=text_file)
            # text_file.write('-'.join(''.join(random.choice(seq) for _ in range(5)) for _ in range(5)) + '\n')

        print("\nCreated {} serial keys.".format(count), file=text_file)
        # text_file.write("\nCreated {} serial keys.\n".format(count))

if __name__ == '__main__':
    main()
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • i get this error: print(file=text_file, '-'.join(''.join(random.choice(seq) for _ in range(5)) for _ in range(5))) ^ SyntaxError: positional argument follows keyword argument – IDONTCODE Feb 11 '21 at 19:40
  • new error: line 20, in main() TypeError: main() missing 2 required positional arguments: 'self' and 'count' – IDONTCODE Feb 11 '21 at 19:44
  • I just started laerning coding and dont know much about pycharm and literally evrything so no – IDONTCODE Feb 11 '21 at 19:49
  • this is my first Code ive ever wrote – IDONTCODE Feb 11 '21 at 19:50
  • So you shouldn't jump to more advanced stuff then you can handle. Take it gradually. Start by going over [The Python Tutorial](https://docs.python.org/3/tutorial/index.html) in order. Then look for some coding challenges websites (there are lots) and start doing some challenges in increasing difficulty – Tomerikoo Feb 11 '21 at 19:52
  • THANK YOU so much for helping me :) – IDONTCODE Feb 11 '21 at 19:53
  • With pleasure. I hope you learned something from this answer. And please do consider my comment above. It will help you advance and save you some frustrations. Also make sure to read about [ask] and how to provide a [mre] before any future questions you ask here. It was hard to figure out with what you're actually struggling. I could only after a long discussion in comments – Tomerikoo Feb 11 '21 at 19:54