Reputation: 41
I`m reading a log file which has several lines and write it to a text file. the output is written to the file as one long line : ['\Bla Bla Bla\n Bla Bla Bla\n'] In original file it looks OK line by line. The reading is done like that:
text_file = open('my_file.log', 'rb')
lines = text_file.readlines()
lines = lines[100:150] #line numbers range
x = open(r"LocalLogFile.txt", "a")
x.write(lines)
Any ideas how to solve it so it will look like original file?
Upvotes: 1
Views: 701
Reputation: 9047
Although other's answer valid a proper way to do this is
with open('my_file.log', 'r') as f1:
# f is an iterator
# so instead of reading the whole file you can
# go to the 100th line
# suppose you you file has thousands of line
for _ in range(100):
next(f1)
# now that you are at 100th line
with open('LocalLogFile.txt', 'a') as f2:
for i in range(50):
f2.write(f1.readline())
# no need to do next(f1 since f1.readline() will call next automatically)
Upvotes: 0
Reputation: 531075
There are several problems here:
Use itertools.islice
to create a new iterator that skips the first 100 lines, then yields the next 400 lines, which you can iterate over using an ordinary for
loop to write to the output file.
from itertools import islice
with open('my_file.log', 'r') as f:
with open('LocalLogFile.txt', 'a') as x:
for line in islice(f, 100, 150):
print(line, file=x, end='')
Some might prefer a single with
statement:
with open('my_file.log', 'r') as f, open('LocalLogFile.txt', 'a') as x:
for line in islice(f, 100, 150):
print(line, file=x, end='')
or
with open('my_file.log', 'r') as f, \
open('LocalLogFile.txt', 'a') as x:
for line in islice(f, 100, 150):
print(line, file=x, end='')
Python 3.10 will make it possible to parenthesize multiple context managers, allowing you to use multiple lines without explicit line continuation:
with (
open('my_file.log', 'r') as f,
open('LocalLogFile.txt', 'a') as x
):
for line in islice(f, 100, 150):
print(line, file=x, end='')
Upvotes: 2
Reputation: 168913
You'd need to write out each line, not the Python representation of a list.
Also, use with
to manage files.
with open('my_file.log', 'rb') as text_file:
lines = list(text_file) # same as readlines
lines = lines[100:150]
with open("LocalLogFile.txt", "a") as x:
x.write("".join(lines))
Upvotes: 2
Reputation: 113948
x.write(''.join(lines))
you are currently writing it as a representation of an array... but you need to write it as a string
Upvotes: -1