Skip to content
Advertisement

How can I go to the next line in .txt file?

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

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

You may also consider enumerate() if you cared about which line a particular value was on, or yielding line[0] to form a generator (which may allow a more efficient process if it can halt before reading the entire file)

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement