Python 文件操作

2020-04-07  本文已影响0人  lc_666

open方法

def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True):

读取、写入文件内容

# 也可以使用stream.readline()来读取一行
# stream.readlines() 将每一行作为元素添加到列表中返回['test\n', 'hello']
stream = open('test.txt')
content = stream.read()
print(content)
stream.close()
# 如输入文件需要换行,可以在字符串尾部添加'\n'
stream.write('hello')
stream.writelines(['how ','are ','you?'])
stream.close()

文件复制

# 使用with结合open,可以自动释放stream资源
with open('/Users/***/Pictures/pap.er/3uDQNn7Jz0w.jpg', mode='rb') as stream:
    content = stream.read()

    with open('/Users/***/Desktop/pic.jpg', mode='wb') as w_stream:
        w_stream.write(content)

print("OK")

os模块

# os.path 中的函数
# 获取当前文件所在的目录,字符串
path = os.path.dirname(__file__)
print(path)  # /Users/****/PycharmProjects/learn

# 拼接路径
path1 = os.path.join(path, 'images/pic.jpg')
print(path1)  # /Users/****/PycharmProjects/learn/images/pic.jpg

# 切割路径,获取文件名
path = '/Users/luchao/Pictures/pap.er/3uDQNn7Jz0w.jpg'
result = os.path.split(path)
print(result)  # ('/Users/***/Pictures/pap.er', '3uDQNn7Jz0w.jpg')

# 切割路径,获取文件后缀名
result = os.path.splitext(path)
print(result)  # ('/Users/***/Pictures/pap.er/3uDQNn7Jz0w', '.jpg')

# 获取文件大小
result = os.path.getsize(path)
print(result)  # 602260 byte

文件夹删除

import os


def dir_truncate(path):
    if os.path.exists(path):
        if os.path.isdir(path):
            if len(os.listdir(path)) != 0:
                for item in os.listdir(path):
                    new_path = os.path.join(path, item)
                    dir_truncate(new_path)

            os.rmdir(path)

        else:
            os.remove(path)

    else:
        print("文件或者文件夹不存在!")

文件夹复制

import os


def dir_copy(sour_path, dest_path):
    if os.path.isfile(sour_path):
        return False
    if not os.path.exists(dest_path):
        os.mkdir(dest_path)

    for item in os.listdir(sour_path):
        new_source_path = os.path.join(sour_path, item)
        new_dest_path = os.path.join(dest_path, item)

        if os.path.isfile(new_source_path):
            with open(new_source_path, mode='rb') as read_stream:
                content = read_stream.read()
                with open(new_dest_path, mode='wb') as write_stream:
                    write_stream.write(content)
        else:
            os.mkdir(new_dest_path)
            dir_copy(new_source_path, new_dest_path)

    return True
上一篇 下一篇

猜你喜欢

热点阅读