Day 10:Python 文件操作

简单介绍一下python中的绝对路径和相对路径:

  绝对路径就是文件的真正存在的路径,是指从硬盘的根目录(盘符)开始,进行一级级

目录指向文件。

  相对路径就是以当前文件为基准进行一级级目录指向被引用的资源文件。 

../ 表示当前文件所在的目录的上一级目录 
./ 表示当前文件所在的目录(可以省略) 
/ 表示当前站点的根目录(域名映射的硬盘目录) 

read_file("C:\Users\user\Documents\PYTHON\python60\test.txt")

文件读操作

通常,再读文件之前,判断文件是否存在。

  • 若文件存在,再读取;
  • 不存在,抛出文件不存在异常。
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

出于安全性考虑,当open后,一定要在合适的位置close, 上面这种写法繁琐,易出错

建议使用with语法,实现open和close功能:

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

文件按行读

read()函数一次读取整个文件,readlines()函数按行一次读取整个文件。

读入文件小时,使用它们没有问题。但是,如果读入文件大,read 或 readlines 一次读取整个文件,内存就会面临重大挑战。

使用 readline 一次读取文件一行,能解决大文件读取内存溢出问题。

文件test.txt如下

1,0,-1,0,0,0,0,0,0
1,-1,0,0,0,0,0,0,0
1,0,0,-1,0,0,0,0,0
3,-1,-1,0,-1,-1,0,1,0
3,-1,0,-1,-1,1,0,-1,0
1,0,0,0,-1,0,0,0,0
1,0,0,0,0,0,-1,0,0
4,-1,-1,-1,-1,0,1,-1,0
6,-2,1,-2,-1,1,-1,-2,0
4,0,-1,-1,-1,-1,1,-1,0
4,0,-1,1,-1,-1,-1,-1,0
4,-1,-1,-1,-1,-1,1,0,0
1,0,0,0,0,0,0,-1,0
4,0,1,-1,-1,-1,-1,-1,0
6,-1,-2,-2,-1,-1,2,-1,0
4,-1,-1,-1,0,-1,1,-1,0
1,0,0,0,0,-1,0,0,0
6,-2,-2,1,-1,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,0,1,0,0,0,0
3,1,-1,1,-1,0,-1,-1,0
6,1,-1,-2,-1,0,-2,2,-2
0,-2,2,1,4,1,-2,2,3
0,1,-1,0,2,2,2,1,-1
1,-1,1,0,1,0,-1,1,1
1,-1,0,1,1,1,-1,0,1
6,1,-2,-1,-1,2,-2,0,-2
3,-1,1,-1,0,-1,-1,1,1
0,0,-1,1,2,2,2,1,-1
0,1,0,-1,2,1,2,2,-1
7,-2,-1,-1,2,-2,0,-2,-1
7,-2,-1,2,-1,-2,-2,0,-1
7,-2,2,-1,-1,0,-2,-2,-1
6,-1,1,1,-2,-1,-1,-1,-2
7,-2,-1,-1,1,-2,1,-2,-1
View Code
  • 每次读入一行。
  • 选择正则 split 分词,注意观察 test.txt,数字间有的一个逗号。这些情况,实际工作中确实也会遇到。
  • 使用 defaultdict 统计数字出现频次。
  • 按照频次从大到小降序。
from collections import  defaultdict
import re

rec = re.compile('D+')
dd = defaultdict(int)
with open("test.txt",'r+') as f:
    for line in f:
        clean_line = line.strip()
        if clean_line:
            words = rec.split(clean_line)
            for word in words:
                dd[word] +=1
dd = sorted(dd.items(), key=lambda x: x[1],reverse=True)
print('---print stat---')
print(dd)
print('---words stat done---')
---print stat---
[('1', 1518), ('0', 675), ('2', 465), ('3', 150), ('4', 73), ('6', 18), ('7', 14), ('5', 13), ('8', 5), ('10', 4), ('9', 4), ('', 2), ('11', 2), ('12', 2)]
---words stat done---

文件写操作

文件写操作时,需要首先判断要写入的文件路径是否存在。

若不存在,通过 mkdir 创建出路径;否则,直接写入文件:

  • 路径不存在,创建路径
  • 写文件
  • 读取同一文件
  • 验证写入到文件的内容是否正确
import os
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)
    to_write_content = ''' 
                        Hey, Python
                        I just love Python so much,
                        and want to get the whole python stack by this 60-days column
                        and believe!
                        '''
    with open(whole_path_filename, mode="w", encoding='utf-8') as f:
        f.write(to_write_content)
    print('-------write done--------')

    print('-------begin reading------')
    with open(whole_path_filename,encoding='utf-8') as f:
        content = f.read()
        print(content)
        if to_write_content == content:
            print('content is equal by reading and writing')
        else:
            print('----Warning: NO Equal-----------------')

获取文件名

有时候拿到一个文件名可能是路径+文件名。

使用os.path、split方法实现(只能是相对)路径和文件的分离。

#file_ext = os.path.split('C:\Users\user\Documents\PYTHON\python60\test.txt')
file_ext = os.path.split('./data/py/test.py')
str_path,str_file = file_ext

获取后缀名

os.path模块splitext方法可以优雅地提取文件后缀。

import os
file_extension = os.path.splitext('./data/py/test.py')
print(file_extension[0],'   ',file_extension[1],type(file_extension[1]))

获取后缀名的文件

import os

def find_file(work_dir,extension='jpg'):
    lst = []
    for filename in os.listdir(work_dir):
        print(filename)
        splits = os.path.splitext(filename)
        ext = splits[1] # 拿到扩展名
        if ext == '.'+extension:
            lst.append(filename)
    return lst

r = find_file('.','txt') 
print(r) # 返回所有目录下的 md 文件
输出为:
day10.ipynb
day10_test_1.txt
day6.ipynb
day7.ipynb
day8.ipynb
day9.ipynb
test.txt
test2.txt
['day10_test_1.txt', 'test.txt', 'test2.txt']   find的结果

批量修改后缀(oops学不会)

将工作目录下的所有后缀名为txt的文件,修改后缀为.c。

使用os模块和argparsem模块

  • 遍历目录下的所有文件
  • 拿到此文件的后缀名
  • 如果后缀名命中为 old_ext,rename 重命名

批量获取文件修改时间

# 获取目录下文件的修改时间
import os
from datetime import datetime

print(f"当前时间:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")

def get_modify_time(indir):
    for root, _, files in os.walk(indir):  # 循环目录和子目录
        for file in files:
            whole_file_name = os.path.join(root, file)
            modify_time = os.path.getmtime(whole_file_name) # 1581164725.991523,这种时间格式太不人性化
            nice_show_time = datetime.fromtimestamp(modify_time) # 转化为人性化的时间显示格式:2020-02-08 20:25:25.991523
            print('文件 %s 最后一次修改时间:%s' %(file,nice_show_time))

get_modify_time('.')的输出为:
文件 day10.ipynb 最后一次修改时间:2021-02-22 20:23:02.266185
文件 day10_test_1.txt 最后一次修改时间:2021-02-22 14:41:56.042538
文件 day6.ipynb 最后一次修改时间:2021-01-10 19:23:38.949160
文件 day7.ipynb 最后一次修改时间:2021-01-13 10:19:54.046079
文件 day8.ipynb 最后一次修改时间:2021-01-13 18:16:23.960555
文件 day9.ipynb 最后一次修改时间:2021-01-19 15:45:23.591995
文件 test.py 最后一次修改时间:2021-02-22 20:15:14.977048
文件 test.txt 最后一次修改时间:2021-02-22 15:15:30.111230
文件 test2.txt 最后一次修改时间:2021-02-22 15:34:23.923736
文件 day10-checkpoint.ipynb 最后一次修改时间:2021-02-22 20:21:13.429037
文件 day6-checkpoint.ipynb 最后一次修改时间:2021-01-10 18:54:06.543796
文件 day7-checkpoint.ipynb 最后一次修改时间:2021-01-12 19:24:42.096080
文件 day8-checkpoint.ipynb 最后一次修改时间:2021-01-13 18:16:23.960555
文件 day9-checkpoint.ipynb 最后一次修改时间:2021-01-19 15:05:03.243948

批量压缩文件

首先导入 zipfile,zipfile是压缩和解压的 Python 模块。

import zipfile
import os 
import time

def batch_zip(start_dir):
    start_dir = start_dir  # 要压缩的文件夹路径
    file_news = start_dir + '.zip'  # 压缩后文件夹的名字
    z = zipfile.ZipFile(file_news, 'w', zipfile.ZIP_DEFLATED)
    for dir_path, dir_names, file_names in os.walk(start_dir):
        # 这一句很重要,不 replace 的话,就从根目录开始复制
        f_path = dir_path.replace(start_dir, '')
        f_path = f_path and f_path + os.sep  # 实现当前文件夹以及包含的所有文件的压缩
        for filename in file_names:
            z.write(os.path.join(dir_path, filename), f_path + filename)
    z.close()
    return file_news  

batch_zip('./zip_test')
'./zip_test.zip'

比较文件找不同,得到行号

# 统计文件个数
def statLineCnt(statfile):
        print('文件名:'+statfile)
        cnt = 0
        with open(statfile, encoding='utf-8') as f:
            while f.readline():
                cnt += 1
            return cnt

# more表示含有更多行数的文件
def diff(more, cnt, less):
            difflist = []
            with open(less, encoding='utf-8') as l:
                with open(more, encoding='utf-8') as m:
                    lines = l.readlines()
                    for i, line in enumerate(lines):
                        if line.strip() != m.readline().strip():
                            difflist.append(i)
            if cnt - i > 1:
                difflist.extend(range(i + 1, cnt))
            return [no+1 for no in difflist]
# 返回的结果行号从 1 开始
# list 表示 fileA 和 fileB 不同的行的编号

def file_diff_line_nos(fileA, fileB):
    try:
        cntA = statLineCnt(fileA)
        cntB = statLineCnt(fileB)
        if cntA > cntB:
            return diff(fileA, cntA, fileB)
        return diff(fileB, cntB, fileA)

    except Exception as e:
        print(e)

if __name__ == '__main__':
    import os
    print(os.getcwd())
    diff = file_diff_line_nos('./a.txt', './b.txt')
    print(diff)  # [4, 5]


a.txt:
hello world
nice to meet you
yes
no1
jack

b.txt:
hello world
nice to meet you
yes

输出:
/home/sage/My Documents/PYTHON/python60
文件名:./a.txt
文件名:./b.txt
[4, 5]
原文地址:https://www.cnblogs.com/PiaYie/p/14430184.html