|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- file_name = input("请输入要打开的文件(C:\\test.txt):")
- file_line = input("请输入需要显示的行数【格式如13:21或:21或21:】:")
- f = open(file_name)
- (begin,end) = file_line.split(":")
- if begin== "":
- begin = 1
- if end == "":
- end = -1
- if file_line.strip == ":":
- begin = "1"
- end = "-1"
- if begin =="1" and end == "-1":
- prompt = "的全文"
- elif begin == "1":
- prompt == "从开始到第%s行"%end
- elif end =="-1":
- prompt == "从第%s行到末尾"%begin
- else:
- prompt == "从第%s行到第%s行"%(begin,end)
- print("文件%s%s的内容如下:")%(file_name,prompt)
- begin= int(begin) - 1
- end = int(end)
- lines = end -1
- for i in range(begin):
- f.readline()
- if lines < 0:
- print(f.read)
- else:
- for j in range(lines):
- print(f.readline(),end="")
- f.close
复制代码
以上是本人写的代码,以下是错误
- 请输入要打开的文件(C:\test.txt):测试1.txt
- 请输入需要显示的行数【格式如13:21或:21或21:】::2
- Traceback (most recent call last):
- File "D:/学校/python exercise/029_3.py", line 23, in <module>
- prompt == "从第%s行到第%s行"%(begin,end)
- NameError: name 'prompt' is not defined
复制代码
我实在不懂为啥prompt还要定义 我看小甲鱼的答案也没有定义,于是我把小甲鱼的答案也拿来跑一下发行也报错。
- 请输入要打开的文件(C:\\test.txt):测试1.txt
- 请输入需要显示的行数【格式如 13:21 或 :21 或 21: 或 : 】::2
- 文件测试1.txt从开始到2的内容如下:
- Traceback (most recent call last):
- File "D:/学校/python exercise/029_3_答案.py", line 43, in <module>
- file_view(file_name, line_num)
- File "D:/学校/python exercise/029_3_答案.py", line 37, in file_view
- print(f.readline(), end='')
- UnicodeDecodeError: 'gbk' codec can't decode byte 0x87 in position 310: illegal multibyte sequence
复制代码
你的错误是因为你写错了,赋值操作符是一个等号,你写了两个等号,就变成比较操作符了
小甲鱼的程序在你那里运行有问题,是因为你的txt文件编码格式不对
open打开文件时,添加一个encoding参数,encoding是指定文件编码格式的
f = open(file_name, encoding='utf-8')
|
|