文件和目录


import os
import zipfile
import shutil
import fnmatch
import glob
import pickle
import io
import shelve
import configparser
""" 
    文件与目录

    os.listdir 查看目录下内容
    os.getcwd   获取当前目录
    os.chdir('')    改变目录
    os.mkdir()      创建目录
    os.path.join()  拼路径
    os.path.exists()    检测路径是否正确
    os.path.isdir()     检测路径是否是目录
    os.path.abspath('.') 绝对路径
    os.path.isabs()   是否是绝对路径
    os.path.relpath()  相对路径
    path.split(os.path.sep)  路径分割
    os.path.basename()  返回文件名
    os.path.dirname()   返回目录名
    os.unlink           删除文件
    shutil.rmtree(path) 删除目录
    copy      复制文件
    copytree  复制目录
    move        移动
    os.path.getsize   获取文件大小
    os.path.isfile()    判断是否是文件
    os.stat     获取文件属性
    获取后缀名的方法
        split
        [-3:]
        re
        endswith
"""

print(os.listdir())
print(os.getcwd())

# os.mkdir('test')
os.chdir('test')
print(os.getcwd())
print(os.path.exists('e:/py'))
print(os.path.isdir('e:/py'))

f = open('test.txt', 'w')
f.close()
fd = os.path.join(os.getcwd(), 'test.txt')
print(fd)
print(os.path.isdir('text.txt'))

print(os.path.abspath('.'))
print(os.path.isabs('e:/'))
print(os.path.relpath(r'e:\py\test\test.txt', 'text.txt'))

path = r'e:\py\test\test.txt'
print(path.split(os.path.sep))  # 每个目录分割
print(os.path.split(path))  # 只分割文件和目录

os.path.basename(path)
os.path.dirname(path)


os.unlink('test.txt')
os.chdir('../')
# shutil.rmtree('test')
# shutil.copytree('test', 'test1')
os.chdir('test')
f = open('test.txt', 'w')
f.close()
shutil.copy('test.txt', 'test2.txt')
shutil.move('test.txt', 'test3.txt')

print(os.path.getsize('test2.txt'))
print(os.path.isfile('test3.txt'))
print(os.stat('test3.txt'))

filename = 'e:/py/test/test2.txt'
print(filename[-3:])
print(os.path.splitext(filename))
print(filename.endswith('txt'))

os.chdir('../')
for root, dirs, files in os.walk('.'):
    # print(root, dirs, files)
    for name in files:
        if name.endswith('py'):
            print(name)

os.chdir('test')

""" 压缩文件 """
my_zip = zipfile.ZipFile('test.zip', 'w')
my_zip.write('test2.txt')
my_zip.write('test3.txt')
my_zip.close()

""" 查看压缩文件 """
dongli = zipfile.ZipFile('test.zip')
print(dongli.namelist())
info = dongli.getinfo('test2.txt')
print(info)
dongli.close()

""" 解压缩 """
dongli = zipfile.ZipFile('test.zip')
dongli.extractall('.')
dongli.close()

"""
    KV编程论:

        文件:增删改查
        处理步骤:打开-操作-关闭
        作用:长期保存数据(办公,娱乐,图像,文本)
        文本用途:简单数据保存,配置文件,日志...
        参考:http://devdocs.io/python~3.6/library/functions#open

    打开方式:

        手动挡open+close:
        open
        close
        自动挡with,自动关闭

    常见操作:

        w,r,a, b
        write
        readline
        readlines
        seek
        tell
        read

    相关模块:

        fnmatch
        glob
        pickle
        StringIO
        shelve
"""

f = open('test5.txt', 'w')
f.write('dongli')
f.close()

f = open('test5.txt', 'r')
r = f.readlines()
print(r)
f.close()

with open('test6.txt', 'w') as f:
    f.write('donglidonglidongli\ndonglidongli')

with open('test6.txt', 'r') as f:
    r = f.readlines()
    print(r)
with open('test6.txt', 'a') as f:
    f.write('\ndonnglialjfdlaf')

with open('test6.txt', 'r') as f:
    r = f.readlines()
    print(r)

f = open('test6.txt', 'r')
print(f.tell())
print(f.readline())
print(f.tell())
print(f.readline())
print(f.tell())
f.seek(0)
print(f.readline())
print(f.tell())

for f in os.listdir():  # 匹配后缀名
    if fnmatch.fnmatch(f, '*.txt'):
        print(f)

for f in glob.glob('test[0-9].txt'):  # 匹配命名规则
    print(f)

a = [1, 2, 3, 4, 5]

with open('test7.pkl', 'wb') as f:  # 序列化
    pickle.dump(a, f)

with open('test7.pkl', 'rb') as f:
    b = pickle.load(f)
print(b)

output = io.StringIO()  # 临时文件
output.write('dongli')
print('test', file=output)  # print到临时文件

content = output.getvalue()
print(content)

""" 用字典的方式存储任意py对象 """

with shelve.open('dongli.she') as so:
    so['dongli'] = 'dashuaige'
    print(so['dongli'])


""" 使用配置文件 """

config = configparser.ConfigParser()
config['DEFAULT'] = {'name': 'dongli'}
config['DEFAULT']['age'] = '18'

config['jiamei'] = {}
config['jiamei']['name'] = 'jiamei'
config['jiamei']['age'] = '1800'

with open('dongli.conf', 'w') as f:
    config.write(f)

print(config.sections())  # 查看字段
print(config['jiamei']['age'])

int(config['jiamei']['age'])  # 转换类型
jiamei = config['jiamei']
print(jiamei.getint('age'))

c = config.read('dongli.conf')
print(c)

with open('dongli.conf', 'r') as f:
    c = f.readlines()
print(c)

config.add_section('dongdong')  # 添加字段
config.set('dongdong', 'name', 'dongdong')

with open('dongli.conf', 'w') as f:
    config.write(f)




最后更新于:2018-06-15 12:52:51