Python Forum

Full Version: Cannot redirect print to a file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
I hope I'm not overstaying my welcome here. Wink
I'm trying to redirect a print statement to a file with no luck.
I have no errors, just nothing is printed to my file.
code:

from itertools import islice

myfile  = 'C:///LogFile.txt'
outfile = open('C://OUTPUT.txt','w')

index = 0
with open(myfile, "r") as f:
    for line in f:
        index += 1
        if "FIND" in line:
            f.seek(0)
            print("".join(islice(f, index - 5, index + 4)))
            outfile.write(''.join(islice(f, index - 5, index + 4)))
             
outfile.close()   
Backslashes are special in strings, but regular slashes are not. You don't need to double them up.

Is it creating the file?

I'd prefer to see you store the string in a variable so you don't have to create it twice.

output = "".join(islice(f, index - 5, index + 4))
print(output)
outfile.write(output)
What does your input file look like?
Awesome, thank you for your help!
It prints to a file.