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將他完成了初步功能但是不夠優化,一起進步吧,歡迎留言

‘’‘

需求:查找某個路徑下的以某個后綴結尾的文件,將其中的某一部分存到指定路徑的文件夾下

’‘’

廢話不多說直接上代碼:如上

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM