您的位置:首页 > 编程语言 > Python开发

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()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: