《笨办法学Python 3》练习20报错:str对象无'read'属性,如何解决?
修复《笨办法学Python 3》练习20中的"str对象没有属性'read'"错误
错误原因
你在调用print_all("Let's print three lines:")时犯了个简单错误:print_all函数设计用来接收文件对象,并调用它的read()方法,但你传了一个字符串进去。字符串类型没有read()属性,所以抛出这个错误。
修复方案
把这行错误的调用改成直接打印提示文本就行——这行本来就是输出一句话,不需要调用读取文件的函数。同时修正原代码里的小笔误("tapea"改成"tape"),修复后的完整代码如下:
from sys import argv from os.path import * script, input_file = argv def print_all(f): print(f.read()) def rewind(f): f.seek(0) def print_a_line(line_count, f): print(line_count, f.readline()) current_file = open(input_file) print("First let's print the whole file:\n") print_all(current_file) print("Now let's rewind, kind of like a tape.") rewind(current_file) # 修改点:直接打印提示文本,无需传给print_all函数 print("Let's print three lines:") current_line = 1 print_a_line(current_line, current_file) current_line = current_line + 1 print_a_line(current_line, current_file) current_line = current_line + 1 print_a_line(current_line, current_file)
验证输出
运行修复后的代码,就能得到你期望的结果:
$ python ex20.py test.txt First let's print the whole file: This is line 1 This is line 2 This line 3 Now let's rewind, kind of like a tape. Let's print three lines: 1 This is line 1 2 This is line 2 3 This is line 3
内容的提问来源于stack exchange,提问作者Rayan Mahmood Chaudhry
相关产品推荐
相关产品推荐

