python-打开文件与读写文件

来源:互联网 发布:域名为什么收费 编辑:程序博客网 时间:2024/06/14 02:21
#!/usr/bin/python# encoding: utf8#with 语句不只是针对文件而言的,它是一个用来创建运行时环境的通用框架(genericframework),告诉对象它们正在进入和离开一个运行时环境。print '\u9fa5'print '\u003f'#创建文件并写入内容with open('test.txt',mode='w') as a_file:a_file.write('test successd')print(a_file.mode)print(a_file.name)with open('test.log', mode='w') as b_file:b_file.write('xxxooo=') #读取文件内容with open('t.txt') as c_file:print(c_file.read()) print(c_file.seek(1)) #seek()方法使定位到文件中的特定字节print(c_file.read(10))#参数表示所读字符的个数print(c_file.tell())#在文件后追加内容with open('test.txt',mode='a') as a_file:a_file.write('and xxx ooo  successd')with open('test.txt') as d_file:print(d_file.read()) #一次读取一行,并打印出行号和数据print '-----------'line_number = 0with open('t.txt') as e_file:for a_line in e_file:line_number += 1print '{0}{1}'.format(line_number,a_line.rstrip())#二进制文件an_image = open('ttt.png', mode='rb')print (an_image.mode)print(an_image.name)print(an_image.encoding)print(an_image.tell())   # 0data = an_image.read(3)  #Nprint (data)print (type(data))  #str ??data = an_image.read()print(len(data))

原创粉丝点击