读取文件内容

利用for循环按行读取文件
import sys

input_file = sys.argv[1]
fileread = open(input_file, 'r', encoding='UTF-8')
line_number = 0
for a in fileread:
    line_number += 1
    print(line_number, a, end='\r')
fileread.close()

encoding=‘UTF-8’ 可以避免出现如下错误:

UnicodeDecodeError: 'gbk' codec can't decode byte 0x81 in position 282: illegal multibyte sequence  

利用while循环读取,按行读取文件

import sys

input_file = sys.argv[1]
fileread = open(input_file, 'r', encoding='UTF-8')
line_number = 0
while True:
    line_number += 1
    line = fileread.readline()
    if line == '':
        break
    print(line_number, line, end='\r')
fileread.close()

  

posted @ 2019-11-03 20:01  魔阳工  阅读(132)  评论(0编辑  收藏  举报