开发者

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

How do you read a character by character from a source file in python until end of li开发者_StackOverflow中文版ne and how do you check for end of line in python so that you can then start reading from the next line and finally how do we check for the end of file condition to finish the read in the entire file. Thank You:).


You can simply iterate over each line in Python. Use the universal end-of-line mode if you want Python to care about Windows/UNIX/Mac line ends automatically:

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 won't have to care about EOL/EOF yourself in this example code.

Note that the line variable includes line endings. If you don't want them, you could use line = line.rstrip(), for example.


You don't have to worry about line and file endings, just do

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜