首页 >>  正文

python中创建txt文件

来源:baiyundou.net   日期:2024-09-21

作者:siseniao

从该文章改进:https://post.smzdm.com/p/an370emp/?zdm_ss=Android_1106136211_&send_by=1106136211&from=other&invite_code=zdmwffzv7winv

原文每次扫描都需要重新计算MD5,对于大文件来说,磁盘消耗较大,增加了缓存文件存储md5,每次扫描只计算新文件,提高效率。

不废话,直接贴代码:

import os

import hashlib

# 只删除以下列表中的重复文件类型.如果想删除其他类型的文件,自己添加一下就行了

file_type = ['.jpg', '.jpeg', '.png', '.gif', '.psd', '.bmp', '.webp', '.mp4', '.mkv', '.avi', '.mov', 'mpeg', 'mpg',
            '.rar', '.zip']
check_files = []

#自行修改目录列表
work_dir_list = [r'/volume2/111', r'/volume1/222']


def save_md5_file(files_dict:dict):
   if files_dict is None:
       return
   try:
       with open("md5.txt", "w") as f:
           for path_md5, file_md5, in files_dict.items():
               f.write(str(path_md5) + "=" + str(path_md5) + 'n')

   except Exception as e:
       pass


def open_md5_file():
   files_md5 = {}
   try:
       with open("md5.txt", "r") as f:
           for md5_line in iter(lambda: f.readline(), ""):
               list_keys = md5_line.split('=')
               if len(list_keys) == 2:
                   files_md5[list_keys[0].strip()] = list_keys[1].strip()
   except Exception as e:
       pass

   return files_md5


def remove_repeat_files():
   for work_dir in work_dir_list:
       for root, dirs, files in os.walk(work_dir):
           for name in files:
               p_type = os.path.splitext(os.path.join(root, name))[1]
               if p_type in file_type:
                   check_files.append(os.path.join(root, name))
           for name in dirs:
               p_type = os.path.splitext(os.path.join(root, name))[1]
               if p_type in file_type:
                   check_files.append(os.path.join(root, name))
   files_dict = {}
   files_md5 = open_md5_file()
   r_index = 0
   print('Files Num:%s' % len(check_files))

   for file_path in check_files:
       try:
           md5_path = hashlib.md5()
           md5_path.update(file_path.encode('utf-8'))
           path_md5 = md5_path.hexdigest()
           file_md5 = files_md5.get(path_md5)
           if file_md5 is None:
               md5_hash = hashlib.md5()
               with open(file_path, "rb+") as f:
                   for byte_block in iter(lambda: f.read(4096), b""):
                       md5_hash.update(byte_block)
                   file_md5 = md5_hash.hexdigest()
               print('Check file MD5:%s' % file_path)
               files_md5[path_md5] = file_md5

           if files_dict.get(file_md5) is None:
               files_dict[file_md5] = file_path
           else:
               d_path = files_dict[file_md5]
               d_path_stats = os.stat(d_path)
               file_stats = os.stat(file_path)
               d_time = d_path_stats.st_ctime
               f_time = file_stats.st_ctime
               if d_time > f_time:
                   os.remove(d_path)
                   files_dict[file_md5] = file_path
                   print('Delete File:', d_path)
                   r_index += 1
               else:
                   os.remove(file_path)
                   print('Delete File:', file_path)
                   r_index += 1
       except Exception as e:
           pass

   print('File Count:%s, Repeat Files Num:%s. All deleted!' %( len(check_files),str(r_index)))
   save_md5_file(files_md5)


if __name__ == '__main__':
   remove_repeat_files()
   


可以在ssh或者任务计划里执行

","gnid":"9a931522e9730c14b","img_data":[{"flag":2,"img":[{"desc":"","height":"385","title":"","url":"https://p0.ssl.img.360kuai.com/t01a2508b2adc68479c.jpg","width":"600"}]}],"original":0,"pat":"art_src_1,fts0,sts0","powerby":"cache","pub_time":1679316661000,"pure":"","rawurl":"http://zm.news.so.com/1715a84bea2900132874605fea6f9a81","redirect":0,"rptid":"71260418b6e0ce01","rss_ext":[],"s":"t","src":"什么值得买","tag":[],"title":"利用python删除群晖重复文件(缓存文件MD5方式)

松霄春4485关于python写入txt文本 -
谭阳奖17276406421 ______ fout=open("test.txt","wt") for i in range(1, 5): s="=>(" c="111," d=i+1 f="," g=12 h=")" print >>fout,i,s,c,d,f,g,h print i,s,c,d,f,g,h fout.close()

松霄春4485求一个用python读取文档中的名字然后创建多个文件夹同时以创建文件夹名字命名的一个txt文件 -
谭阳奖17276406421 ______ 代码如下,就是这么简单: import os basepath = 'c:\data'; for line in open('a.txt'): basename = line.strip() folder = os.path.join(basepath, basename) filename = os.path.join(folder, basename) os.mkdir(folder) open(filename, 'w').close() 望采纳,谢谢支持!

松霄春4485python创建文件 -
谭阳奖17276406421 ______ 语法错误. 在你希望输出错误信息那里(ERROR)需要一个print. 如果Python2.* : print "ERROR:...." 如果Python3.* : print("ERROR...")

松霄春4485python3.6不能创建文件 -
谭阳奖17276406421 ______ 需要以写方式创建文件:with open('1.txt','w') as f:如果当前目录下1.txt不存在则会创建文件.

松霄春4485python 一个变量里是字符串和数列,如何把字符串写到txt文件里? -
谭阳奖17276406421 ______ 字符串和list之间,是不能直接加的. list=[5,6,10] str1="" for i in list: str1+=str(i)+',' aa="游戏结果:"+str1 print(aa) file = open("C:/py.txt","a") file.write(aa)

松霄春4485Python无法新建文件? -
谭阳奖17276406421 ______ 首先,在win10搜索框搜索到IDLE,然后点击运行IDLE便可以了.打开时候是处于测试模式的,这种模式比较友好,可以随意测试.而如果想要编辑一个比较正规的python文件就需要新建了,“Ctrl+N”便是idle的文件新建了.之后,便会多出一个窗口,这个窗口不同于第一次打开的窗口,这个窗口可以编辑python代码了. 默认是untitled,所以要Ctrl+S保存好它才可以.保存时默认就是Python File类型保存好之后就是写上正规的Python代码了,这里我直接用print测试.

松霄春4485安装了python记事本改变了格式还闪了几下还是打不开? -
谭阳奖17276406421 ______ 您好,python是一种编程语言,记事本是创建txt文件用的.改变txt文档的格式在python的编译器里应该是不能直接打开的.

松霄春4485用python 列出指定目录下所有的txt文件,并输出每个文件的创建日期和大小 -
谭阳奖17276406421 ______ #!/usr/bin/python import os import re import time dir = "." type = "txt" files = os.listdir( dir ) rr = re.compile( "\.%s$" %type , re.I ) for f in files: if rr.search(f): info = os.stat( f ) print "File : [%s]" %f ctime = time.localtime( info.st_ctime ) print "\...

松霄春4485Python中如何创建文件 -
谭阳奖17276406421 ______ open(filename,'w')或open(filename,'wb')

松霄春4485python 求一个编程建立一个新的file -
谭阳奖17276406421 ______ # -*- coding:utf-8 -*- fname=raw_input('Please input filename:\n') with open(fname+'.txt','w') as f1: with open('fp.txt','r') as f2: for i in f2: f1.write(i) f1.write('\nhello world')

(编辑:自媒体)
关于我们 | 客户服务 | 服务条款 | 联系我们 | 免责声明 | 网站地图 @ 白云都 2024