Skip to content Skip to sidebar Skip to footer

Reading A File Until A Specific Character In Python

I am currently working on an application which requires reading all the input from a file until a certain character is encountered. By using the code: file=open('Questions.txt','r'

Solution 1:

The easiest way would be to read the file in as a single string and then split it across your separator:

withopen('myFileName') as myFile:
  text = myFile.read()
result = text.split(separator)  # use your \-1 (whatever that means) here

In case your file is very large, holding the complete contents in memory as a single string for using .split() is maybe not desirable (and then holding the complete contents in the list after the split is probably also not desirable). Then you could read it in chunks:

defeach_chunk(stream, separator):
  buffer = ''whileTrue:  # until EOF
    chunk = stream.read(CHUNK_SIZE)  # I propose 4096 or soifnot chunk:  # EOF?yield buffer
      break
    buffer += chunk
    whileTrue:  # until no separator is foundtry:
        part, buffer = buffer.split(separator, 1)
      except ValueError:
        breakelse:
        yield part

withopen('myFileName') as myFile:
  for chunk in each_chunk(myFile, separator='\\-1\n'):
    print(chunk)  # not holding in memory, but printing chunk by chunk

Solution 2:

I used "*" instead of "-1", I'll let you make the appropriate changes.

s = '1.Hai\n2.Bye*3.Hello\n4.OAPd*'
temp = ''
results = []

forcharin s:
    ifcharis'*':
        results.append(temp)
        temp = []
    else:
        temp += chariflen(temp) > 0:
    results.append(temp)

Post a Comment for "Reading A File Until A Specific Character In Python"