把字符串“2021”写入c:\test.txt文件中,查看文件的长度(字节数);在文件头部插入自己的“十位学号”,然后在文件尾部添加自己的“姓名”。
再把该文件内容复制到d:\testbak.txt中;最后把d:\testbak.txt的内容显示出来。(最后两步操作要求使用With open() as f:的方式完成)
import os,sys,stat
file = 'C:\\test.txt'
file2 = 'D:\\testbak.txt'
with open(file,'w') as f:
f.write('2021')
print('test.txt字节数:',os.path.getsize(file))
sno = '2019211410'
name = '张三'
with open(file,'r+') as f:
old = f.read()
f.seek(0)
f.write(sno+' ')
f.write(old)
f.write(' '+name)
content = ''
with open(file,'r') as f:
content = f.read()
with open(file2,'w') as f:
f.write(content)
print('testbak.txt内容:',content)