利用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=' ') 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=' ') fileread.close()