How can I read only first symbol in each line with out reading all line, using python? For example, if I have file like:
apple pear watermelon
In each iteration I must store only one (the first) letter of line.
Result of program should be ["a","p","w"]
, I tried to use file.seek()
, but how can I move it to the new line?
Advertisement
Answer
file-like objects are iterable, so you can directly use them like this
collection = [] with open("input.txt") as fh: for line in fh: # iterate by-lines over file-like try: collection.append(line[0]) # get the first char in the line except IndexError: # line has no chars pass # consider other handling # work with collection
You may also consider enumerate()
if you cared about which line a particular value was on, or yield
ing line[0]
to form a generator (which may allow a more efficient process if it can halt before reading the entire file)
def my_generator(): with open("input.txt") as fh: for lineno, line in enumerate(fh, 1): # lines are commonly 1-indexed try: yield lineno, line[0] # first char in the line except IndexError: # line has no chars pass # consider other handling for lineno, first_letter in my_generator(): # work with lineno and first_letter here and break when done