Home > database >  Writing my function to a txt file return 'None' in txt file but the desired result in term
Writing my function to a txt file return 'None' in txt file but the desired result in term

Time:01-08

I understand that this is a newbie question, I am a newbie. I have a function that takes a list of URLs and formats them into HTML tables. I want the output of the function to be on an existing TXT file. I tried putting the function as the .write input but it only writes 'None' in the file. I understood that its because my function is basically empty as it only write and keeps it nowhere, but i have trouble solving that. using the return instead of print doesn't work. The function does write the result into the Terminal prefectly.

def test2(strList):
  d = defaultdict(int)
  for k in strList:
    d[k]  = 1
  print('<table>')
  for i in d.items():
    print(
      '<tr><td><img src="{0[0]}"</td><td><img src="{0[1]}"</td></tr>'.format(i))
  print('</table>')

and thats the writing code

f = open("albumshtml.txt", "w")
f.write(str(test2(img)))
f.close()

ive tried using append instead of w, same result. how can i save the function without printing until i want it to write to the TXT file? again, im new to it don't scold me please.

CodePudding user response:

An alternative to returning the string is to pass the file you want to write to as an argument (which can default to sys.stdout to preserve the current behavior).

import sys
import contextlib


def test2(strList, f=sys.stdout):
    d = defaultdict(int)
    for k in strList:
        d[k]  = 1
    print('<table>', file=f)
    for i in d.items():
        print(
          '<tr><td><img src="{0[0]}"</td><td><img src="{0[1]}"</td></tr>'.format(i), file=f)
    print('</table>', file=f)


with open("albumshtml.txt", "w") as f:
    test2(img, f)

with open("albumshtml.txt", "w") as f:
    with contextlib.redirect_stdout(f):
        test2(img)

The redirect_stdout trick can also be used without modifying test2, since print writes to sys.stdout when the file keyword argument is not used.

You can also use redirect_stdout inside test2 to avoid having to repeat the file argument on every call to print.

def test2(strList, f=sys.stdout):
    d = defaultdict(int)
    for k in strList:
        d[k]  = 1
    with contextlib.redirect_stdout(f):
        print('<table>')
        for i in d.items():
            print(
              '<tr><td><img src="{0[0]}"</td><td><img src="{0[1]}"</td></tr>'.format(i))
        print('</table>')


with open("albumshtml.txt", "w") as f:
    test2(img, f)

CodePudding user response:

You can use a list to save the result and finally use the method str.join to concatenate the string elements in the list.

def test2(strList):
    d = defaultdict(int)
    for k in strList:
        d[k]  = 1
    res_list = ['<table>']
    for i in d.items():
        res_list.append(
            '<tr><td><img src="{0[0]}"</td><td><img src="{0[1]}"</td></tr>'.format(i)
        )
    res_list.append('</table>')
    return "".join(res_list)

  •  Tags:  
  • Related