美文网首页
Python 文件操作

Python 文件操作

作者: lc_666 | 来源:发表于2020-04-07 17:19 被阅读0次

open方法

def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True):
  • mode
    • The default mode is 'rt' (open for reading text).
    • 'r' open for reading (default)
    • 'w' open for writing, truncating the file first
    • 'x' create a new file and open it for writing
    • 'a' open for writing, appending to the end of the file if it exists
    • 'b' binary mode
    • 't' text mode (default)
    • '+' open a disk file for updating (reading and writing)
    • 'U' universal newline mode (deprecated)

读取、写入文件内容

  • 读取
# 也可以使用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

相关文章

  • 14.Python之文件操作

    Python之文件操作 文件操作通过Python中的内置函数open()对文件进行操作。文件操作需要如下几个参数:...

  • 第二节课:Python 操作文件 ——软件测试派

    学习目标:掌握 python 操作文件 python 提供内置函数 open()实现对文件的操作。 python ...

  • Python遍历目录并操作文件

    今天来使用python操作文件,包括根据模式查找文件、删除文件操作。 完整代码托管在python/find...

  • 解析Python中的文件操作

    1.简介 在Python中无需引入额外的模块来进行文件操作,Python拥有内置的文件操作函数(除了内置文件操作函...

  • Python 文件操作

    一. Python 读写 创建文件 Python中对文件,文件夹(文件操作函数)的操作需要涉及到OS 模块和 sh...

  • Python

    Python 创建文件 Python 对数据库进行操作--增删改查 Python 对csv进行操作 Python ...

  • python常用文件操作总结

    python 移动文件或文件夹操作。python中对文件、文件夹操作时经常用到的os模块和shutil模块常用方法...

  • python--文件的基本操作

    python编程中,文件是必不可少的。下面我们来学习python中文件的基本操作。 文件的基本操作: 在pytho...

  • Python常用语法二

    Python 字符串操作和文件操作以及其它Python能力补充 Python字符串操作 in和not in: 'x...

  • 文件操作

    Python基础教程 文件内容操作 python中的文件操作还是挺简单的,类似于php中的文件方法,精简好用。我们...

网友评论

      本文标题:Python 文件操作

      本文链接:https://www.haomeiwen.com/subject/hswnphtx.html