笨办法16读写文件
2017-08-30 17:46
246 查看
代码如下:
运行结果:
新增的文件内容:
注:
‘w’:以只写模式打开。若文件存在,则会自动清空文件,然后重新创建;若文件不存在,则新建文件。使用这个模式必须要保证文件所在目录存在,文件可以不存在。该模式下不能使用read*()方法
加分练习2:代码如下
运行结果:
加分练习3:写了两种方法
加分练习4:找出为什么我们需要给 open 多赋予一个 ‘w’ 参数。提示: open 对于文件的写入操作态度是安全第一,所以你只有特别指定以后,它才会进行写入操作。
因为默认open只能读取不能写入,所以要写入内容就必须加入’w’参数。
truncate()其实是不需要的,因为open的参数是w
#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
相关文章推荐
- 笨办法学python习题16 读写文件
- 《笨办法学 python3》系列练习计划——16.读写文件
- 在mac下配置tp5,出现文件读写权限的问题解决办法
- 笨方法学python16习题 【读写文件】 最详解
- python读写UCS-2 big/little endian(utf-16-be/utf-16-le)格式的文件
- Java基础(16):IO流—采用RandomAccessFile类读写文件,功能更强
- 关于“使用xmlspy编写xsl文件时候,在xsl解释xml文件的时候总是使用utf-16编码”的解决办法
- python读写unicode文件之utf-16
- linux c 读写超过2G的大文件解决办法
- Learn Python The Hard Way学习(16) - 读写文件
- C#技巧【调用线程无法访问此对象,因为另一个线程拥有该对象的问题的解决办法】【C#读写EXCEL源码提示“office检测到此文件存在一个问题。为帮助保护您的计算机,不能打开此文件”的解决】
- python16 文件的读写
- 《笨办法学python》习题16:读写文件
- EACCES (permission denied)解决办法 android 文件读写
- Java读写UTF-16 little Endian文件
- C++16、文件读写
- Android 6.0系统读写文件出现FileNotFoundException:EACCES (permission denied)解决办法
- php读写txt文件与读写数据库哪个更快?解决办法
- 文件磁盘相关函数[16]-文本文件读写-覆写文件 Rewrite
- 【Android开发小记--16】assets、raw、内部存储、外部存储——文件的读写