文件
1.文件的打开和关闭, 文件的读,写和追加
1 f=open("test","w")
2 content=f.write("the life is short , you need python")
3 print(content)
4 f.close()
5 f=open("test","r")
6 content=f.read(5)
7 print(content)
8 content=f.read()
9 print(content)
10 f.close()
11 f=open("test","a")
12 content=f.write("python is easy")
13 print(content)
14 f.close
2.文件的定位
1 f=open("test","r")
2 content=f.read(3)
3 print(content)
4 position=f.tell()
5 print(position)
6 f.seek(3,0)
7 content=f.read()
8 print(content)
9 f.close()
注意:seek不能从非零定位,具体原因有待查证,见下次更新:在文本文件中,没有使用b模式选项打开的文件,只允许从文件头开始计算相对位置,从文件尾计算时就会引发异常。
3.文件及文件夹的相关操作
f=open("test","r")
import os #导入os模块
文件重命名 os.rename(oldname,newname)
文件删除 os.remove(文件名)
创建文件夹 os.mkdir(文件名)
获取当前目录 os.getcwd()
改变默认目录 os.chdir()
获取目录列表 os.listdir()
删除文件夹 os.redir()
4.文件的备份
1 oldfile_name=input("输入要备份的文件名:")
2 old_file=open(oldfile_name,"r")
3 position=oldfile_name.rfind(".")
4 newfile_name=oldfile_name[:position]+"备份"+oldfile_name[position:]
5 new_file=open(newfile_name,"w")
6 while True:
7 content=old_file.read(1)
8 if len(content) == 0:
9 break
10 new_file.write(content)
11 old_file.close()
12 new_file.close()
网友评论