-1

I want print my output to text file. Jow can I fix my code?

for h3 in parse.find_all('h3', {'class': "_1hETr2dodrTLejwpCPNjNp"}):
     account = '{}:{}:{}'.format(ab_form, ft_form, h3.get_text())
     print(account)
     output = open("./output.txt", "r")
     output.write(account)
martineau
  • 119,623
  • 25
  • 170
  • 301
blacko
  • 3
  • 3
  • 1
    To begin with, you should open the file only once, and in write mode. – mkrieger1 Jul 04 '19 at 22:35
  • 2
    Possible duplicate of [Correct way to write line to file?](https://stackoverflow.com/questions/6159900/correct-way-to-write-line-to-file) – user1781290 Jul 04 '19 at 23:22
  • See this [answer](https://stackoverflow.com/a/56875363/355230) to a similar question. In Python 3.4+ you can use the built-in [`contextlib.redirect_stdout`](https://docs.python.org/3/library/contextlib.html#contextlib.redirect_stdout) context manager. – martineau Jul 04 '19 at 23:39

2 Answers2

1

You need a + in your file open to create the file if it does not exist.

Also, there is little value opening the file each time through the loop.

with open("./output.txt", "a+") as fd:
  for h3 in parse.find_all('h3', {'class': "_1hETr2dodrTLejwpCPNjNp"}):
    account = '{}:{}:{}\n'.format(ab_form, ft_form, h3.get_text())
    fd.write(account)

I will assume that the rest of the script does what you need it to do.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
GMc
  • 1,764
  • 1
  • 8
  • 26
0
    for h3 in parse.find_all('h3', {'class': "_1hETr2dodrTLejwpCPNjNp"}):
        account = '{}:{}:{}\n'.format(ab_form, ft_form, h3.get_text())
        with open("./output.txt", "a") as fd:
            fd.write(account)

note \n newline separator and 'a' append mode as you are doing multiple writes

garyboland
  • 135
  • 12