文件、目录的基本操作,在python使用中非常广泛。还是边练习边深入。
目录操作相关:
#获得完整路径
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()
文件操作相关:
#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()