课后作业29题,求助大佬
def file_reader(name,num):list1 = num.split(sep = ':')
began = list1
last = list1
f1 = open(name)
if began == ' ':
if last ==' ':
print('文件%s的全文内容如下:' % name)
print(f1.read())
else:
print('文件%s从开头到第%s行的内容如下:')
lines = int(last)
while lines:
print(f1.readline())
lines -= 1
elif began != ' ':
time1 = int(began)
time1.1 = time1
while time1 != 1:
f1.readline()
time1 -= 1
if last == ' ':
print('文件%s从第%s行到末尾的内容如下:' % (name,began))
print(f1.read())
else:
time2 = int(last)
time3 = time2 - time1.1 + 1
print('文件%s从第%s行到第%s行的内容下所示:' % (name,began,last))
while time3:
print(f1.readline())
time3 -= 1
f1.close()
name = input('请输入需要打开的文件:')
num = input('请输入需要显示的行数:')
file_reader(name,num)
会报错
Traceback (most recent call last):
File "D:\phython\课后作业29 3.py", line 36, in <module>
file_reader(name,num)
File "D:\phython\课后作业29 3.py", line 20, in file_reader
f1.readline()
UnicodeDecodeError: 'gbk' codec can't decode byte 0xad in position 26: illegal multibyte sequence
解码问题,试一下给open函数加上encoding = 'utf-8'参数
def file_reader(name,num):
list1 = num.split(sep = ':')
began = list1
last = list1
f1 = open(name,'r',encoding = 'utf-8')
if began == ' ':
if last ==' ':
print('文件%s的全文内容如下:' % name)
print(f1.read())
else:
print('文件%s从开头到第%s行的内容如下:')
lines = int(last)
while lines:
print(f1.readline())
lines -= 1
elif began != ' ':
time1 = int(began)
time1_1 = time1
while time1 != 1:
f1.readline()
time1 -= 1
if last == ' ':
print('文件%s从第%s行到末尾的内容如下:' % (name,began))
print(f1.read())
else:
time2 = int(last)
time3 = time2 - time1_1 + 1
print('文件%s从第%s行到第%s行的内容下所示:' % (name,began,last))
while time3:
print(f1.readline())
time3 -= 1
f1.close()
name = input('请输入需要打开的文件:')
num = input('请输入需要显示的行数:')
file_reader(name,num)
页:
[1]