Using readline with a new delimiter of line ?

L

Laurent

Hello,

is it possible to read a file in python line by line
by redefining a new end-of-line delimiter ?

I would like for example to have the string "END" being the new delimiter
for each line.

Thanks
 
R

remco

Laurent said:
is it possible to read a file in python line by line
by redefining a new end-of-line delimiter ?

I would like for example to have the string "END" being the new delimiter
for each line.

i couldn't find any builtin option. But of course you could always use:


listOfLines = file('<filename>','r').read().split('END')

Cheers!
remco
 
L

Laurent

thanks for this
Laurent

remco said:
i couldn't find any builtin option. But of course you could always use:


listOfLines = file('<filename>','r').read().split('END')

Cheers!
remco
 
D

Duncan Booth

Hello,

is it possible to read a file in python line by line
by redefining a new end-of-line delimiter ?

I would like for example to have the string "END" being the new delimiter
for each line.
If your file is short enough that it will fit comfortably into memory, just
do:

inputFile = file('name', 'rb')
lines = inputFile.read().split('END')

then you can iterate over the list stored in 'lines'.

If the file is too large for that, you'll need to implement your own scheme
to read chunks, split them up on your delimiter and return a line at a
time. The easiest way to do that is to use a generator. Something like:

def oddFile(filename, delimiter, buffersize=10000):
inputFile = file(filename, 'rb')
lines = ['']
for data in iter(lambda: inputFile.read(buffersize), ''):
lines = (lines[-1] + data).split(delimiter)
for line in lines[:-1]:
yield line
yield lines[-1]

Then you can do:

for l in oddFile('somefile', 'END'):
print repr(l)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top