Python Forum
Cannot redirect print to a file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Cannot redirect print to a file
#1
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()   
Reply
#2
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)
Reply
#3
What does your input file look like?
Reply
#4
Awesome, thank you for your help!
It prints to a file.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Cannot get cmd to print Python file Schauster 11 3,548 May-16-2024, 04:40 PM
Last Post: xMaxrayx
  redirect STDIO in the Python code Skaperen 6 3,176 Jul-05-2023, 12:23 AM
Last Post: Skaperen
  Saving the print result in a text file Calli 8 4,480 Sep-25-2022, 06:38 PM
Last Post: snippsat
  failing to print not matched lines from second file tester_V 14 9,394 Apr-05-2022, 11:56 AM
Last Post: codinglearner
  Print to a New Line when Appending File DaveG 0 1,752 Mar-30-2022, 04:14 AM
Last Post: DaveG
Sad Want to Save Print output in csv file Rasedul 5 16,039 Jan-11-2022, 07:04 PM
Last Post: snippsat
  Convert legacy print file to XLSX file davidm 1 2,621 Oct-17-2021, 05:08 AM
Last Post: davidm
  Why it does not print(file.read()) Rejaul84 1 3,374 Jul-01-2021, 10:37 PM
Last Post: bowlofred
  stderr redirect to file fmr300 2 5,561 Apr-03-2021, 01:31 AM
Last Post: fmr300
  get two characters, count and print from a .txt file Pleiades 9 5,324 Oct-05-2020, 09:22 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020