python查找读写文件

 1 import os
 2 '''
 3 跟据文件名称,后缀查找指定文件
 4 path:传入的路径
 5 filename:要查找的文件名
 6 suffix:要查找的文件后缀
 7 return  :返回查找的文件路径
 8 '''
 9 
10 
11 filenamepath = ''
12 
13 
14 def find_file(path, filename, suffix):
15     global filenamepath
16     filelist = os.listdir(path)
17     for i in range(0, len(filelist)):
18         file_path = os.path.join(path, filelist[i])
19         if os.path.isdir(file_path):
20             find_file(file_path, filename, suffix)
21         elif os.path.splitext(file_path)[1] == '.'+suffix and os.path.splitext(file_path)[0].split('\\')[-1] == filename:
22             filenamepath = filenamepath+file_path
23     return filenamepath
24 
25 '''
26 根据文件路径,截取指定文件内容
27 filenamepath:文件路径
28 splitcontent:要分割的节点
29 return:返回截取的内容
30 '''
31 
32 def readfile(filenamepath, splitcontent):
33     file_open = open(filenamepath)
34     try:
35         file_content = file_open.read()
36         # print(file_content)
37         newcontent = file_content.split(splitcontent)[0]
38         # print('s1为:',s1)
39     finally:
40         file_open.close()
41     return newcontent
42 
43 '''
44 将内容写进指定文件
45 writepath:写入文件的路径
46 suffix:写入文件的格式
47 newcontent:写入的内容
48 '''
49 def writefile(writepath,suffix, newcontent):
50     if not os.path.exists(writepath):
51         os.makedirs(writepath)
52     writepathsuffix = writepath+'.'+suffix
53     file = open(writepathsuffix, 'w')
54     try:
55         file.write(newcontent)
56     finally:
57         file.close()

最近工作中遇到一个小需求,使用python将他完成了初步功能但是不够优化,一起进步吧,欢迎留言

‘’‘

需求:查找某个路径下的以某个后缀结尾的文件,将其中的某一部分存到指定路径的文件夹下

’‘’

废话不多说直接上代码:如上

猜你喜欢

转载自www.cnblogs.com/jiyanjiao-702521/p/9227615.html