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
  redirect STDIO in the Python code Skaperen 6 1,289 Jul-05-2023, 12:23 AM
Last Post: Skaperen
  Saving the print result in a text file Calli 8 1,783 Sep-25-2022, 06:38 PM
Last Post: snippsat
  failing to print not matched lines from second file tester_V 14 6,069 Apr-05-2022, 11:56 AM
Last Post: codinglearner
  Print to a New Line when Appending File DaveG 0 1,217 Mar-30-2022, 04:14 AM
Last Post: DaveG
Sad Want to Save Print output in csv file Rasedul 5 10,906 Jan-11-2022, 07:04 PM
Last Post: snippsat
  Convert legacy print file to XLSX file davidm 1 1,801 Oct-17-2021, 05:08 AM
Last Post: davidm
  Why it does not print(file.read()) Rejaul84 1 2,330 Jul-01-2021, 10:37 PM
Last Post: bowlofred
  stderr redirect to file fmr300 2 3,569 Apr-03-2021, 01:31 AM
Last Post: fmr300
  get two characters, count and print from a .txt file Pleiades 9 3,354 Oct-05-2020, 09:22 AM
Last Post: perfringo
  redirect url_for passing arguments with the url Leon79 1 1,647 Jul-09-2020, 05:20 PM
Last Post: Leon79

Forum Jump:

User Panel Messages

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