博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Python基础 - 07文件操作

Posted on 2021-10-14 22:16  Kingdomer  阅读(57)  评论(0编辑  收藏  举报

Python基础 - 07文件操作

一、文件操作

1.1 操作模式

mode: 

r-> read 读,               w-> write 写                ----> 纯文本文件         

rb-> read binary 二进制读    wb-> write binary 二进制写   ----> 图片、音乐、电影

a->  追加                   t-> text mode(default)      x->  新增文件进行写操作         + ---> 打开一个文件进行写操作

输入、输出:   (read)in:  从文本到内存             (write) out: 从内存到文本

 

1.2 读操作

read():      读取所有内容

readline():  每次读取一行内容

readlines(): 读取所有的行保存到列表中

readable():  判断是否可读

stream = open(r'e:\app\aa.txt')
container = stream.read()
print(container)             # 读取所有的内容

result = stream.readable()
print(result)                # True

line1 = stream.readline()
print(line1)                 # 111 \n
line2 = stream.readline()
print(line2)                 # 2222 \n

while True:
    line = stream.readline()
    print(line)
    if not line:
        break
print('文件读取完毕!')           
"""
111

2222

33333

文件读取完毕!
"""                     

 

# 保存到列表中
lines = stream.readlines()
print(lines)               # ['111\n', '2222\n', '33333']
for i in lines:
    print(i)

  

1.3 写操作

write():       每次都会将原来的内容清空,然后再写入新内容

writelines():  没有换行效果,需要使用"\n"来换行

stream = open(r'e:\app\aa.txt','w')
s="""abcd
1234"""

result = stream.write(s)
print(result)             # 9, 写入的字符数量
stream.write('黄山') stream.writelines('泰山\n') stream.writelines(['衡山\n','嵩山\n']) stream.close() # 释放资源

  

# a:  追加
stream = open(r'e:\app\aa.txt','a')
stream.write('新追加内容1\n')
stream.close()
stream = open(r'e:\app\aa.txt','r')
lines = stream.readlines()
print(lines)          # ['abcd\n', '1234黄山泰山\n', '衡山\n', '嵩山\n', '新追加内容1\n']
stream.close()

  

# 拷贝二进制文件
# with open():  等同于  r_stream = open(r'e://app/background07.jpg','rb'); r_stream.close()
with open(r'e://app/background07.jpg','rb') as r_stream:
    ch = r_stream.read()

    with open(r'e://app//py01.jpg', 'wb') as w_stream:
        w_stream.write(ch)

print('文件拷贝完成!')

  

二、 OS模块

os.getcwd() / chdir() / listdir() / mkdir() / rmdir() / remove() / path

2.1 os.path 文件操作

import random
import os
print(os.path)                      # <module 'ntpath' from 'D:\\Program Files\\Python39\\lib\\ntpath.py'>
# 获取当前文件所在的文件目录
path = os.path.dirname(__file__)
print(path)                         # E:\PythonLearn\pythonBase\02door2
print(type(path))                   # <class 'str'>
full_file_path = os.path.join(path, 'aa.jpg') print(full_file_path) # E:\PythonLearn\pythonBase\02door2\aa.jpg
# 将文件拷贝当前目录下,保持原文件名 with open(r'e:\\app\\background07.jpg','rb') as r_stream: ch = r_stream.read() src_file = r_stream.name #print(src_file) # e:\\app\\background07.jpg filename = src_file[src_file.rfind("\\")+1:] path = os.path.dirname(__file__) dst_file = os.path.join(path, filename) with open(dst_file, 'wb') as w_stream: w_stream.write(ch) print('文件拷贝完成!')

  

import os

# 是否为绝对路径 r = os.path.isabs(r'e:\\app\\background07.jpg') print('----> ', r) # ----> True r = os.path.isabs(r'background07.jpg') print('----> ', r) # ----> False # 当前的文件的绝对路径 path1 = os.path.abspath('background017.jpg') print(path1) # E:\PythonLearn\pythonBase\02door2\background017.jpg
# 获取当前目录 path2 = os.getcwd() # 类似于 os.path.dirname(__file__) print(path2) # E:\PythonLearn\pythonBase\02door2 r1 = os.path.isfile(os.getcwd()) print(r1) # False r2 = os.path.isdir(os.getcwd()) print(r2) # True

  

# 分割目录和文件
path3 = r'E:\PythonLearn\pythonBase\02door2\background07.jpg'
result = os.path.split(path3)
print(result)                # ('E:\\PythonLearn\\pythonBase\\02door2', 'background017.jpg')
# 分割文件名与文件后缀
result = os.path.splitext(path3)
print(result)                # ('E:\\PythonLearn\\pythonBase\\02door2\\background017', '.jpg')
# 获取文件的大小,单位字节
size = os.path.getsize(path3)
print(size)                  # 845472

result = os.path.join(os.getcwd(), 'images','py01','aa.jpg')
print(result)                # E:\PythonLearn\pythonBase\02door2\images\py01\aa.jpg

  

2.2 os模块

# 返回指定目录下的所有文件和文件夹,保存到列表中
all = os.listdir(r'e:\\app')
print(all)                 # ['aa.txt', 'background07.jpg', 'logs', 'py01.jpg']
# 创建文件夹: 存在时, FileExistsError: [WinError 183] 当文件已存在时,无法创建该文件。 f = os.mkdir(os.path.join(os.getcwd(),'images')) print(f) # None
# 删除文件夹: 不存在时, FileNotFoundError: [WinError 2] 系统找不到指定的文件。 # rmdir / removedirs 文件夹不为空报错 OSError: [WinError 145] 目录不是空的。 f = os.rmdir(os.path.join(os.getcwd(),'images')) print(f) # None f = os.removedirs(os.path.join(os.getcwd(),'images')) print(f)

  

# 删除不为空的文件夹, 文件夹下全是文件
path = os.path.join(os.getcwd(), 'images')
all = os.listdir(path)
for file in all:
    file_path = os.path.join(path, file)
    os.remove(file_path)
else:
    os.rmdir(path)

f = os.chdir(r'e:\\')
print(f)           # None
path = os.getcwd()
print(path)        # e:\
all = os.listdir(path)
print(all)         # [...,'0 - 我的学习', '1 - Java', '2 - MySQL', '3 - Python',...]

  

实现文件拷贝功能:可拷贝文件夹

 

def copy_function(src_path, dest_path):
    if not os.path.exists(dest_path):
        os.mkdir(dest_path)
    if os.path.isdir(src):
        file_list = os.listdir(src_path)

        for file in file_list:
            path = os.path.join(src_path, file)
            if os.path.isdir(path):
                # 递归调用
                dest_sub_path = os.path.join(dest_path, file)
                if not os.path.exists(dest_sub_path):
                    os.mkdir(dest_sub_path)
                copy_function(path, dest_sub_path)
            else:
                # 是普通文件
                with open(path, 'rb') as r_stream:
                    char = r_stream.read()
                    path2 = os.path.join(dest_path, file)
                    with open(path2, 'wb') as w_stream:
                        w_stream.write(char)
                print(path + '文件复制完毕')
        else:
            print(src_path + '--->路径下文件复制完毕')
    else:
        print('输入的文件不是目录')

src = r'E:\app\pp-src'
dest = r'E:\app\copy-test6'

copy_function(src, dest)

'''
E:\app\pp-src\a1.txt文件复制完毕
E:\app\pp-src\aa\aa1.txt文件复制完毕
E:\app\pp-src\aa\aaaa\sc.doc文件复制完毕
E:\app\pp-src\aa\aaaa --->路径下文件复制完毕
E:\app\pp-src\aa --->路径下文件复制完毕
E:\app\pp-src\background07.jpg文件复制完毕
E:\app\pp-src\bb --->路径下文件复制完毕
E:\app\pp-src --->路径下文件复制完毕
'''