def fun(txt,number):
f = open(txt)
for each in range(int(number)):
print(f.readline(),end = '')
print('\n文件%s的前%d行的内容如下:'%(txt,number))
f.close()
txt = input('请输入要打开的文件:')
number = input('请输入需要显示该文件前几行:')
fun(txt,number)
====================== RESTART: C:\Users\ASUS\Desktop\3.py =====================
请输入要打开的文件:E:something.txt
请输入需要显示该文件前几行:5
Traceback (most recent call last):
File "C:\Users\ASUS\Desktop\3.py", line 15, in <module>
fun(txt,number)
File "C:\Users\ASUS\Desktop\3.py", line 5, in fun
print(f.readline(),end = '')
UnicodeDecodeError: 'gbk' codec can't decode byte 0xae in position 4: illegal multibyte sequence
汉字编码问题,打开文件的语句 改成下面这样试试 f = open(txt , encoding = 'UTF-8')
|