【Python】Learn Python the hard way, ex16 读写文件

本文探讨了在Python中进行文件读写的方法,重点对比了两种不同的操作方式,指出方法2更为实用。通过open函数配合指定参数,可以避免使用truncate()函数来清空文件。
摘要由CSDN通过智能技术生成
# coding:utf-8
#方法1
'''
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, 'w')

print "Truncating the file. Goodby!"
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()
'''
#方法2
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, 'w')

print "Truncating the file. Goodby!"
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 + "\n" + line2 + "\n" + line3 + "\n")

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


'''
Test Result:

We're going to erase '/Users/GaoHongxing/Desktop/ex16 sample.txt'.
If you don't want that, hit CTRL-C(^C).
If you do want that, hit RETURN.
?
Opening the file...
Truncating the file. Goodby!
Now I'm going to ask you for three lines.
line 1: Mary had a little lamb
line 2: It's fleece waw white these to the file.
line 3: It was also tasty
I'm going to write these to the file.
And finally, we close it.
'''


心得:

1, 方法2更实用

2, open函数使用了参数,就不再需要truncate()函数(清空文件)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
"Learn Python the Hard Way" 是一本非常受欢迎的Python编程入门教材,由Zed Shaw编著。虽然很多人推荐这本书,但是可能有人会想要获取中文版的PDF。 实际上,"Learn Python the Hard Way" 的官方版本只有英文版,目前没有官方中文翻译。然而,你仍然可以通过互联网上的其他资源找到非官方的中文翻译版本。在很多技术论坛和编程社区上,都有Python爱好者提供自己的中文翻译版本,一些电子书资源网站上也有非官方的中文PDF版本。 要找到中文翻译版,你可以在搜索引擎中输入相关关键词,比如 "learn python the hard way 中文pdf" 或者 "learn python the hard way 中文翻译"。在搜索结果中,你可能会找到一些免费的资源供你下载或在线阅读。此外,还有一些网站提供付费的中文翻译版本,你可以根据自己的需求决定是否购买。 无论你选择哪种方式,记得要确认翻译版本的质量和真实性。可以通过查看评论、评级或者与其他Python学习者交流来了解其他人对于该版本的评价。另外,虽然中文翻译版本对于初学者会有一定帮助,但如果你有能力阅读英文,最好还是参考官方英文版来学习,以避免因为翻译的不准确而导致的误解或困惑。 总而言之,虽然"Learn Python the Hard Way"的官方版本只有英文版,但你可以通过互联网查找一些非官方的中文翻译版本。希望你能够找到一本合适的中文翻译版本,顺利学习Python编程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值