Cannot redirect print to a file - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Cannot redirect print to a file (/thread-29467.html) |
Cannot redirect print to a file - tester_V - Sep-04-2020 Hi, I hope I'm not overstaying my welcome here. 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() RE: Cannot redirect print to a file - bowlofred - Sep-04-2020 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) RE: Cannot redirect print to a file - micseydel - Sep-04-2020 What does your input file look like? RE: Cannot redirect print to a file - tester_V - Sep-11-2020 Awesome, thank you for your help! It prints to a file. |