Python基础 - 07文件操作

发布时间:2022-07-03 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Python基础 - 07文件操作脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

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:appaa.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)               # ['111n', '2222n', '33333']
for i in lines:
    print(i)

  

1.3 写操作

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

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

stream = open(r'e:appaa.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:appaa.txt','a')
stream.write('新追加内容1n')
stream.close()
stream = open(r'e:appaa.txt','r')
lines = stream.readlines()
print(lines)          # ['abcdn', '1234黄山泰山n', '衡山n', '嵩山n', '新追加内容1n']
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:PythonLearnpythonBase2door2
print(type(path))                   # <class 'str'>
full_file_path = os.path.join(path, 'aa.jpg')
print(full_file_path)               # E:PythonLearnpythonBase2door2aa.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:PythonLearnpythonBase2door2background017.jpg
# 获取当前目录
path2 = os.getcwd()         # 类似于 os.path.dirname(__file__)
print(path2)                # E:PythonLearnpythonBase2door2

r1 = os.path.isfile(os.getcwd())
print(r1)                   # False

r2 = os.path.isdir(os.getcwd())
print(r2)                   # True

  

# 分割目录和文件
path3 = r'E:PythonLearnpythonBase2door2background07.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:PythonLearnpythonBase2door2imagespy01aa.jpg

  

2.2 os模块

# 返回指定目录下的所有文件和文件夹,保存到列表中
all = os.listdir(r'e:\app')
print(all)                 # ['aa.txt', 'background07.jpg', 'LOGs', 'py01.jpg']
# 创建文件夹: 存在时,  FileExistsError: [@R_879_2406@rror 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:apppp-src'
dest = r'E:appcopy-test6'

copy_function(src, dest)

'''
E:apppp-srca1.txt文件复制完毕
E:apppp-srcaaaa1.txt文件复制完毕
E:apppp-srcaaaaaasc.doc文件复制完毕
E:apppp-srcaaaaaa --->路径下文件复制完毕
E:apppp-srcaa --->路径下文件复制完毕
E:apppp-srcbackground07.jpg文件复制完毕
E:apppp-srcbb --->路径下文件复制完毕
E:apppp-src --->路径下文件复制完毕
'''

 

  

 

 

脚本宝典总结

以上是脚本宝典为你收集整理的Python基础 - 07文件操作全部内容,希望文章能够帮你解决Python基础 - 07文件操作所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。