python 笔记 读写文件——12.26
来源:互联网 发布:在淘宝怎么买电棍 编辑:程序博客网 时间:2024/05/22 11:33
今天很开心,发现csdn可以直接发代码,之前一直羡慕别人可是不会发。
习题 16: 读写文件
目标与感悟:
• close – 关闭文件。跟你编辑器的 文件 -> 保存 .. 一个意思。
• read– 读取文件内容。你可以把结果赋给一个变量。
•readline – 读取文本文件中的一行。
•truncate – 清空文件,请小心使用该命令。
• write(stuff) – 将 stuff 写入文件
ex16.py
#-*- coding:utf-8-*-from sys import argv script,filename = argv #这里提示到的CTRL-C和再次敲击RETURN应该是内置的,我并没有看到定义。print "We're going to erase %r." % filenameprint "If you don't want that, hit CTRL-C (^C)."print "If you do want that, hit RETURN." raw_input("?") print "Opening the file..."#这里使用了open,open(路径+文件名,读写模式)#读写模式可以分为:r 只读,r+读写,w新建(会覆盖原有文件)#a追加,b二进制#常用模式'rb','wb','r+b'target = open(filename, 'w') print "Truncating the file. Goodbye!"#truncate,我感觉多余了,因为oepn的参数w就有新建覆盖的意思target.truncate() print "Now I'm going to ask you for three lines." #让用户输入3个句子,并将其赋予给3个变量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." #将3个变量写入文件中,并且每写完一个换行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()
运行结果:
test.txt
It's a good day!
How are you?
I need to shave itoff.
感悟与自我测试:
ex16_1.py
#-*-coding: utf-8-*-from sys import argv script, filename = argv print "Let's go to test!"print "Now,erase the %r." %filenameprint "If you don't want that, hit CTRL-C (^C)."print "If you do want that, hit RETURN." raw_input(">???") #此处的路径需要多加一个\,因为python中的\另有用处,所以需要转义。print "In \test\,creating and opening the file..."target = open('C:\\Users\\gyl\\test\\test1\\%s'%filename,'w') #我感觉没必要,所以先令其失效,事后也证明是对的。#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("Continue line 2:") print "I'm going to write these to the file." #此处我并没有在第二行之后进行换行,所以应该是只有2行target.write(line1)target.write("\n")target.write(line2)target.write(line3) print "And finally, we close it." #close,很容易理解就是关闭的意思。target.close()
运行结果:
test.txt
This is the firstline!
This is the secondline!This is also second line!
阅读全文