码迷,mamicode.com
首页 > 其他好文 > 详细

笨办法16读写文件

时间:2017-10-10 23:17:54      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:用户   rip   技术   text   tin   指定   size   ...   语句   

代码如下:

 1 #coding:utf-8
 2 from sys import argv
 3 
 4 script, filename = argv
 5 
 6 print "We‘re going to erase %r." %filename #提示语句,告知用户将抹掉文件
 7 print "If you don‘t want that, hit CTRL-C (^C)." #提示语句,停止操作的按键
 8 print "If you do want that, hit RETURN." #提示语句,继续操作的按键
 9 
10 raw_input("?") #让用户输入是否要继续操作
11 
12 print "Opening the file..." #提示语句,正在打开文件
13 target = open(filename, w) #将打开的文件清空并赋值给target,w不能大写
14 
15 print "Truncating the file. Goodbye!" #提示语句,正在清空文件
16 target.truncate() #执行清空文件操作#truncate()其实是不需要的,因为open的参数是w
17 
18 print "Now I‘m going to ask you for three lines." #提示语句
19 
20 line1 = raw_input("line 1:") #输入第一行的内容
21 line2 = raw_input("line 2:") #输入第二行的内容
22 line3 = raw_input("line 3:") #输入第三行的内容
23 
24 print "I‘m going to write these to the file." #提示语句
25 
26 target.write(line1) #写入第一行的内容
27 target.write("\n") #写入换行符
28 target.write(line2)
29 target.write("\n")
30 target.write(line3)
31 target.write("\n")
32 
33 print "And finally, we close it." #提示关闭文件
34 target.close() #关闭(保存)文件

运行结果: 
技术分享

新增的文件内容: 
技术分享

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


加分练习2:代码如下

1 print "Please enter your filename, and I‘ll read it."
2 
3 filename = raw_input(">")
4 txt = open(filename)
5 print txt.read()

运行结果: 
技术分享


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

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

加分练习4:找出为什么我们需要给 open 多赋予一个 ‘w’ 参数。提示: open 对于文件的写入操作态度是安全第一,所以你只有特别指定以后,它才会进行写入操作。 
因为默认open只能读取不能写入,所以要写入内容就必须加入’w’参数。 
truncate()其实是不需要的,因为open的参数是w

笨办法16读写文件

标签:用户   rip   技术   text   tin   指定   size   ...   语句   

原文地址:http://www.cnblogs.com/p36606jp/p/7648183.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!