python-打开文件与读写文件
#!/usr/bin/python# encoding: utf8#with 语句不只是针对文件而言的,它是一个用来创建运行时环境的通用框架(genericframework),告诉对象它们正在进入和离开一个运行时环境。print '\u9fa5'print '\u003f'#创建文件并写入内容with open('test.txt',mode='w') as a_file:a
·
#!/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 = 0
with open('t.txt') as e_file:
for a_line in e_file:
line_number += 1
print '{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()) # 0
data = an_image.read(3) #N
print (data)
print (type(data)) #str ??
data = an_image.read()
print(len(data))
更多推荐



所有评论(0)