How to parse a file line by line, char to char in Python?

How do you read the character by character from the source file in python to the end of the line and how do you check the end of the line in python so that you can then start reading from the next line and finally how we check the end of the file condition to finish reading in the whole file. Thanks:).

+1
source share
2 answers

You can just iterate over each line in Python. Use the universal end of line mode, if you want Python to take care of the Windows / UNIX / Mac line, it automatically ends:

with open("mytextfile.txt", "rtU") as f: for line in f: # Now you have one line of text in the variable "line" and can # iterate over its characters like so: for ch in line: ... # do something here 

You do not need to take care of EOL / EOF yourself in this code example.

Note that the line variable includes line endings. If you do not want them, you can use line = line.rstrip() , for example.

+8
source

You do not need to worry about the completion of lines and files, just do

 file = open('yourfile', 'r') for line in file.readlines(): for c in line: # do sth. 
+1
source

Source: https://habr.com/ru/post/1301192/


All Articles