#file操作要点:针对桌面的aaa.txt
with open(r‘C:\\Users\\xuyin\\Desktop\\aaa.txt‘,‘r‘)as f:
x1=f.read() #得到一个字符串
print type(x1)
print(x1)
f.seek(0,0)
print(1)
x2=f.readline()#得到第一行,形成字符串
print type(x2)
print(x2)
# f.seek(0,0),没有这行则读取剩下的全部行
print(f.readlines()) #得到一个列表,每行作为一个元素
with open(r‘C:\\Users\\xuyin\\Desktop\\aaa.txt‘,‘w+‘)as f:
f.write(‘what do you like?\\nboth‘)#清空原来的重新写
f.writelines(‘123\\n‘)#接着写,
f.writelines(‘thank you‘)
f.seek(0,0)
print(1)
print f.read()
ans:
<type ‘str‘>
what do you like?
both123
thank you
1
<type ‘str‘>
what do you like?
[‘both123\\n‘, ‘thank you‘]
1
what do you like?
both123
thank you
remark:没有f.wirteline
#从末尾开始写:
with open(r‘C:\\Users\\xuyin\\Desktop\\aaa.txt‘,‘a+‘)as f:
f.write(‘see you!‘)
f.seek(0,0)
print(f.read())
ans:
what do you like?
both123
thank yousee you!
文件读取类型:??
w:只写
r:
w+
r+
a+:追加
遇到二进制的后面加‘b‘:rb,wb...