Python学习---文件目录操作
2011-05-26 11:21
211 查看
文件、目录的基本操作,在python使用中非常广泛。还是边练习边深入。
目录操作相关:
文件操作相关:
目录操作相关:
''' Created on 2011-5-26 @author: Administrator ''' import os.path dir = "C://pyFileTest" def testDir(): #获得当前目录 cur = os.path.curdir print(cur) #获得完整路径 full =os.path.abspath(os.path.curdir) print(full) print(os.getcwd()) #获得基本路径(最末路径) print(os.path.basename(full)) #获得目录下的文件和目录,剔除'.'和'..' a = os.listdir(dir) #切换到该目录 os.chdir(dir) for f in a: #判断是否为文件或者目录 if (os.path.isdir(f) == True): print("it's a dir, the name is: " ,f) else : print("it's a file, the file size is: " , os.path.getsize(f)) #创建目录 os.mkdir("newdir") #递归遍历整个目录 #返回3元组,root顶层目录,dirs为root目录下的子目录(不含","和".."),files为root目录下的文件 #列出个目录下文件的大小 for root, dirs, files in os.walk(dir, True, None, False): print("the dir is: " , root) sum = 0 for f in files : prefix = os.path.splitext(f)[1] print('the file type is: ' , prefix) name = os.path.splitext(f)[0] print('the file name is: ', name) sum += os.path.getsize(os.path.join(root,f)) print(sum) if __name__ == '__main__': testDir()
文件操作相关:
''' Created on 2011-5-26 @author: Administrator ''' def TestFile(): #打开文件,读取每一行 #其中需要用try...finally进行读取的异常处理 path = "C://pyFileTest//" file = path + "test.txt" f = open(file) try: for l in f: print(l,) finally: f.close() #tell()方法为文件当前的pointer指针位置 #seek()方法进行文件定位 #先读取一行,然后在文件定位到开始 f = open(file) try: print(f.readline()) print("the current file pointer is:", f.tell()) f.seek(0) print(f.read(3)) finally: f.close() #在文件中追加数据 f = open(file, "a+") try: f.write("/n=====") finally: f.close() #创建文件 dest = "newfile.txt" f = open(path + dest, 'w') try: f.write("this is a new file") finally: f.close() if __name__ == '__main__': TestFile()
相关文章推荐
- Python学习一:文件/目录操作合集
- python 学习笔记(一)—目录文件的操作
- Python学习笔记(18)-目录操作与文件读写
- 廖雪峰python学习笔记13.操作文件和目录
- python学习——操作文件和目录
- python学习笔记 操作文件和目录
- 【Python学习笔记】IO编程:操作文件和目录
- python学习笔记 操作文件和目录
- Python学习:IO基础(2):对文件目录的操作
- python 文件与目录的操作 未完善 需要重新学习
- python学习笔记 目录和文件操作
- python的学习笔记之对文件、目录的操作
- Python的学习笔记14------操作文件和目录
- Python3学习(31)--文件和目录的操作
- Python基础-操作文件和目录
- Linux系统学习第二章:文件与目录操作(三):文件操作
- Python学习笔记3-文件的简单操作
- paip.文件目录操作uAPI php python java对照
- 《转》Python学习(15)-对文件的操作(二)
- Python 文件目录操作