Python中的文件操作

文件读操作

读取文件,要先判断文件是否存在。

import os


def read_file(filename):
    if os.path.exists(filename) is False:
        raise FileNotFoundError('%s not exists' % (filename,))
    f = open(filename, encoding='utf-8')
    content = f.read()
    f.close()
    return content


print(read_file('D:/git/README.md'))

输出结果:

<font size='4'>下面是一些简单的学习demo</font>

注意,在调用open的时候,尽量指定编码格式,一般采用UTF-8,避免在打开的时候报编码的错。

文件按行读

read 函数一次读取整个文件,readlines 函数按行一次读取整个文件。如果读入文件大,read 或 readlines 一次读取整个文件,内存就会面临重大挑战。

所以,可以使用 readline 一次读取一行。

test.txt 文本的内容是:

What is   perfect? 
It's the volume of   the headphones that   just covers the outside noise. 
When   the alarm clock rings, 
you just   wake up    naturally, 
and the   person   you love   just loves you

翻译:

什么是完美?就是耳机音量刚好能盖过外界噪音,闹钟响起时你刚好自然醒,你爱的人刚好也爱你。

读取 test.txt 文件,使用 r+ 读写模式,需求:

  • 每次读入一行。
  • 选择正则 split 分词,单词间有的一个空格,有的多个。去掉多余的空格。
  • 使用 defaultdict 统计单词出现频次。
  • 按照频次从大到小降序。
from collections import defaultdict
import re

rec = re.compile('\s+')
count = defaultdict(int)
with open('C:/Users/xxx/Desktop/test.txt', 'r+', encoding='utf-8') as f:
    for line in f:
        print(line)
        clean_line = line.strip()
        if clean_line:
            words = rec.split(clean_line)
            for word in words:
                count[word] += 1
count = sorted(count.items(), key=lambda x: x[1], reverse=True)
print(count)

输出结果:

What is   perfect? 

It's the volume of   the headphones that   just covers the outside noise. 

When   the alarm clock rings, 

you just   wake up    naturally, 

and the   person   you love   just loves you
--Statistics of frequency of occurrence--
[('the', 5), ('just', 3), ('you', 3), ('What', 1), ('is', 1), ('perfect?', 1), ("It's", 1), ('volume', 1), ('of', 1), ('headphones', 1), ('that', 1), ('covers', 1), ('outside', 1), ('noise.', 1), ('When', 1), ('alarm', 1), ('clock', 1), ('rings,', 1), ('wake', 1), ('up', 1), ('naturally,', 1), ('and', 1), ('person', 1), ('love', 1), ('loves', 1)]
文件写操作

文件写操作时,需要首先判断要写入的文件路径是否存在。 若不存在,通过 mkdir 创建出路径;否则,直接写入文件。

  • 文件路径不存在,创建路径。
  • 然后写文件。
  • 读取同一文件。
  • 验证写入到文件的内容是否正确。
def write_to_file(file_path, file_name):
    if os.path.exists(file_path) is False:
        os.mkdir(file_path)

    whole_path_filename = os.path.join(file_path, file_name)
    write_content = '''我的小鱼,你醒了,还认识早晨吗?昨夜你曾经说,愿夜幕永不开启。
    你的香腮边轻轻滑落的,是你的泪,还是我的类?初吻吻别的那个季节,不是已经哭过了吗?
    我的指尖还记忆着,你慌乱的心跳。温柔的体香里,那一缕长发飘飘'''
    with open(whole_path_filename, mode='w', encoding='utf-8') as f:
        f.write(write_content)
    print('--write finish--')

    print('--read begin--')
    with open(whole_path_filename, encoding='utf-8') as f:
        content = f.read()
        print(content)
        if write_content == content:
            print('content is equal')
        else:
            print('-- NO Equal --')


write_to_file('C:/Users/xxx/Desktop', 'c.txt')

输出结果:

--write finish--
--read begin--
我的小鱼,你醒了,还认识早晨吗?昨夜你曾经说,愿夜幕永不开启。
    你的香腮边轻轻滑落的,是你的泪,还是我的类?初吻吻别的那个季节,不是已经哭过了吗?
    我的指尖还记忆着,你慌乱的心跳。温柔的体香里,那一缕长发飘飘
content is equal
获取文件名

有时拿到一个文件名时,名字带有路径。这时,使用 os.path、split 方法实现路径和文件的分离。

file_ext = os.path.split('./xxx/desktop/c.py')
path, fileName = file_ext
print(f'文件路径: {path},文件名:{fileName}')

输出结果:

文件路径: ./xxx/desktop,文件名:c.py
获取后缀名

os.path 模块,splitext 能够优雅地提取文件后缀。

file_suffix = os.path.splitext('./xxx/desktop/c.py')
print('路径前缀:%s,后缀:%s' % (file_suffix[0], file_suffix[1]))

输出结果:

路径前缀:./xxx/desktop/c,后缀:.py
获取指定后缀名的文件

从指定目录中,获取指定后缀名的所有文件。

def find_file(work_dir, suffix='jpg'):
    lst = []
    for filename in os.listdir(work_dir):
        print(filename)
        splits = os.path.splitext(filename)
        split_suffix = splits[1]
        if split_suffix == '.' + suffix:
            lst.append(filename)
    return lst


print(find_file('E:/test', 'py'))

输出结果:

a.py
abc.xlsx
accc.txt
b.py
dadsadas.docx
['a.py', 'b.py']
XLS 批量转换成 XLSX

 .xls 的文件批量转换成 .xlsx 

def xls_to_xlsx(work_dir):
    old_ext, new_ext = '.xls', '.xlsx'
    for filename in os.listdir(work_dir):
        split_file = os.path.splitext(filename)
        file_ext = split_file[1]

        if old_ext == file_ext:
            new_file = split_file[0] + new_ext
            # 重命名
            os.rename(os.path.join(work_dir, filename), os.path.join(work_dir, new_file))
    print(os.listdir(work_dir))


print('--修改之前的目录--')
print(os.listdir('E:/test'))
print('--修改之后的目录--')
xls_to_xlsx('E:/test')

输出结果:

--修改之前的目录--
['a.py', 'abc.xls', 'accc.txt', 'adadad.xls', 'b.py', 'dadsadas.docx']
--修改之后的目录--
['a.py', 'abc.xlsx', 'accc.txt', 'adadad.xlsx', 'b.py', 'dadsadas.docx']
获取所有文件的最后一次修改时间

os.walk 生成文件树结构,os.path.getmtime 返回文件的最后一次修改时间。

def get_modify_time(dir):
    # 循环目录和子目录
    for root, _, files in os.walk(dir):
        for file in files:
            whole_file_name = os.path.join(root, file)
            modify_time = os.path.getatime(whole_file_name)
            show_time = datetime.fromtimestamp(modify_time)
            print('文件 %s 最后一次修改时间:%s' % (file, show_time))


get_modify_time('E:/test')

输出结果:

当前时间:2020 - 07 - 20 09: 17: 44
文件 a.py 最后一次修改时间:2020-07-17 17:02:57.920739
文件 abc.xlsx 最后一次修改时间:2020-07-20 09:01:46.837401
文件 accc.txt 最后一次修改时间:2020-07-17 17:03:40.137717
文件 adadad.xlsx 最后一次修改时间:2020-07-20 09:01:14.269801
文件 b.py 最后一次修改时间:2020-07-17 17:03:07.257614
文件 dadsadas.docx 最后一次修改时间:2020-07-17 17:03:50.959324
批量压缩文件

zipfile这个模块是来进行压缩的。

def zip_file(work_dir):
    # 压缩的文件路径
    start_dir = work_dir
    # 压缩后文件夹的名字
    file_new_name = start_dir + '.zip'
    z = zipfile.ZipFile(file_new_name, 'w', zipfile.ZIP_DEFLATED)
    for dir_path, dir_names, file_names in os.walk(start_dir):
        file_path = dir_path.replace(start_dir, '')
        # 实现当前文件夹以及包含的所有文件的压缩
        file_path = file_path and file_path + os.sep
        for filename in file_names:
            z.write(os.path.join(dir_path, filename), file_path + filename)
        z.close()
        return file_new_name


print(zip_file('E:/test'))

输出结果:

E:/test.zip

执行完上面的代码,在本地文件夹就可以看到打印结果显示的压缩包了。

文件加密

hashlib 模块支持多种文件的加密策略。这里将采用MD5加密策略。

# 对字符串 进行 32位数的加密
def hash_32(s):
    m = hashlib.md5()
    m.update((str(s).encode('utf-8')))
    return m.hexdigest()


print(hash_32(2))
print(hash_32('the'))

输出结果:

c81e728d9d4c2f636f067f89cc14862c
8fc42c6ddf9966db3b09e84365034357
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值