How can I read only first symbol in each line with out reading all line, using python? For example, if I have file like:
JavaScript
x
4
1
apple
2
pear
3
watermelon
4
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
JavaScript
1
11
11
1
collection = []
2
3
with open("input.txt") as fh:
4
for line in fh: # iterate by-lines over file-like
5
try:
6
collection.append(line[0]) # get the first char in the line
7
except IndexError: # line has no chars
8
pass # consider other handling
9
10
# work with collection
11
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)
JavaScript
1
11
11
1
def my_generator():
2
with open("input.txt") as fh:
3
for lineno, line in enumerate(fh, 1): # lines are commonly 1-indexed
4
try:
5
yield lineno, line[0] # first char in the line
6
except IndexError: # line has no chars
7
pass # consider other handling
8
9
for lineno, first_letter in my_generator():
10
# work with lineno and first_letter here and break when done
11