Search code examples
python-3.xtextreturn

Output text file contains only last letter of the expected result


I'm trying to get the output which is a huge string file. I'm using the following code to generate the text file, but only the last letter of the expected output is been generated. I'm using .loc as well to segregate the input file and generate a file containing only specified row.

>     for l in Y:
>       print(l, end = '')
>     
>     with open("abc.txt", "w") as text_file:
>       print(f'> \n{l}', file=text_file)

I'm getting the following result:

> K That's it. I'm expecting the output to be a series of strings such as:

> ABCD...K

Any help will be highly appreciated.


Solution

  • The problem occurs because you use a f-string (f"> \n{l}") to format your text, and you pass the l variable to this f-string. Though your l variable was set for the last time in the last iteration of the previous loop, then you are printing the last item of Y in your file.

    The correct syntax would be:

     with open("abc.txt", "w") as text_file:
         print(f'> \n{Y}', file=text_file) 
    

    Or, maybe it is your indentation that is wrong and you meant to do this:

     for l in Y:
       print(l, end = '')
    
       with open("abc.txt", "w") as text_file:
         print(f'> \n{l}', file=text_file)
    

    Besides, I would recommend to do something like this instead:

    with open("abc.txt", "w") as f:
        for l in Y:
            f.write(f'> {l}\n')
    

    Or even better, if possible:

    with open("abc.txt", "w") as f:
        f.writelines(Y)