编辑和阅读文件(LPTHW练习16)

时间:2018-01-29 14:28:29

标签: python

我一直在Zed Shaw的“学习Python困难之路”一书中练习16,我做了一个小脚本试着看看我是否完全理解它。然而,我陷入了一个小部分,我希望你们能够帮助...这是我正在做的参考练习:

from sys import argv

script, filename = argv

print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."

raw_input("?")

print "Opening the file..."
target = open(filename, 'r+')
print "Displaying the file contents:"
print target.read()

print "Truncating the file. Goodbye!"
target.truncate()

print "Now i'm going to ask you for three lines."

line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")

print "I'm going to write these to the file."

target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")

print "And finally, we close it."
target.close()

这是我的代码,

from sys import argv
script, user_name, filename = argv

print "Hello %r! I'm the %r script!" % (user_name, script)
print "Well %r, today we're going to do something very special!" % user_name
print "What are we going to do? Well you'll find out! Press ENTER to 
continue after the prompts!"

raw_input(">")

print "We are going to learn how to read and overwrite files today %r!" % 
user_name
print "Now, let's open and read what's in this file %r?" % filename
target = open(filename)
print target.read()

#The output reads:
#HELLO ITS ME

raw_input(">")

print "Phew! Now that was a handful"
print "Now let's erase all of that!"
abc = open(filename, 'w')

print "Now I'm going to ask you for 2 new lines!"
line1 = raw_input("Line 1: ")
line2 = raw_input("Line 2: ")

#Line 1: HELLO ITS NOT ME THIS TIME
#Line 2: NOOOOO

abb = abc.write("%r\n%r" % (line1, line2))
print abb.read()

这个脚本背后的想法是我想为自己编写一个基本教程来展示3件事: 1)我希望脚本读取并打印出基本的notepad.txt文件 2)我希望脚本截断这个基本的记事本文件&将2行原始输入写入此文件 3)我希望脚本打印出新文件

现在有些问题, 我对这个脚本最紧迫的问题是我无法运行最后几行,而是出现错误:

Traceback(most recent call last):
File "ex3.py", line27, in <module>
print abb.read()
AttributeError: 'NoneType' object has no attribute 'read'

有人能够对此事提出一些启示吗?我对编程完全陌生,所以请耐心解释!我也意识到社区认为LPTHW并不是开始进行python学习的最佳书籍,但我决定试一试作为我的第一个编程入门!提前致谢!

2 个答案:

答案 0 :(得分:0)

解释器正在告诉你究竟是什么问题:File.write什么都不返回,即它返回None,你不能在None类型上调用read()方法。删除“abb =”,然后更改

print abb.read()

print abc.read()

它应该可以正常工作。

答案 1 :(得分:0)

您似乎对写入文件时返回的内容感到困惑。如果在写入文件时检查返回到abb的内容,您会发现它是一个整数,表示您写入文件的字符数。

abb = abc.write("%r\n%r" % (line1, line2))

在此行之后,整数存储在abb

print abb.read()

当您尝试在abb(整数)上运行read方法时,这可能会产生错误,指示您的整数对象没有读取方法。

如果您希望在写入文件后查看已写入的文件,则需要最初以读写模式打开文件,或者关闭文件以便写入并从新文件对象中读取。

abc.write("%r\n%r" % (line1, line2))
abc.close()
abb = open(filename, 'r')
print abb.read()
abb.close()