您的位置:首页 > 其它

笨办法16读写文件

2017-08-30 17:46 246 查看
代码如下:

#coding:utf-8
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') #将打开的文件清空并赋值给target,w不能大写

print "Truncating the file. Goodbye!" #提示语句,正在清空文件
target.truncate() #执行清空文件操作#truncate()其实是不需要的,因为open的参数是w

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() #关闭(保存)文件


运行结果:



新增的文件内容:



注:

‘w’:以只写模式打开。若文件存在,则会自动清空文件,然后重新创建;若文件不存在,则新建文件。使用这个模式必须要保证文件所在目录存在,文件可以不存在。该模式下不能使用read*()方法

加分练习2:代码如下

print "Please enter your filename, and I'll read it."

filename = raw_input(">")
txt = open(filename)
print txt.read()


运行结果:



加分练习3:写了两种方法

#target.write(line1+"\n"+line2+"\n"+line3) #变量不需加引号,字符串需要加双引号#a+b参考第6课
target.write("%s\n%s\n%s" % (line1, line2, line3)) #这里如果用%r,文件的每行字符会有引号


加分练习4:找出为什么我们需要给 open 多赋予一个 ‘w’ 参数。提示: open 对于文件的写入操作态度是安全第一,所以你只有特别指定以后,它才会进行写入操作。

因为默认open只能读取不能写入,所以要写入内容就必须加入’w’参数。

truncate()其实是不需要的,因为open的参数是w
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: