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?
Feel like you're not getting the answers you want? Checkout the help/rules for things like what to include/not include in a post, how to use code tags, how to ask smart questions, and more.

Pro-tip - there's an inverse correlation between the number of lines of code posted and my enthusiasm for helping with a question :)
Reply
#4
Awesome, thank you for your help!
It prints to a file.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  get two characters, count and print from a .txt file Pleiades 9 533 Oct-05-2020, 09:22 AM
Last Post: perfringo
  redirect url_for passing arguments with the url Leon79 1 337 Jul-09-2020, 05:20 PM
Last Post: Leon79
  Redirect to __stdout__ fails in IDLE shell Pavel_47 1 389 Apr-13-2020, 05:13 PM
Last Post: deanhystad
  Print/write to file function tpolim008 4 627 Apr-01-2020, 07:59 PM
Last Post: tpolim008
  Print date, Time and output to file tpolim008 3 542 Mar-26-2020, 06:49 PM
Last Post: ndc85430
  Look for match in two files and print out in the first file Batistuta 0 416 Mar-03-2020, 02:27 PM
Last Post: Batistuta
  Print a JSON file mrobie 5 1,179 May-31-2019, 09:38 PM
Last Post: Yoriz
  Print to Text file in Python 3 iteachpc 2 956 May-02-2019, 04:38 AM
Last Post: perfringo
  Print random musik to wav file Pereskia 2 861 Mar-27-2019, 11:53 AM
Last Post: Pereskia
  Help with try and open 6.txt file and print as perfect or not Pleiades 13 1,832 Jan-03-2019, 10:14 PM
Last Post: Pleiades

Forum Jump:

User Panel Messages

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