生活随笔
收集整理的這篇文章主要介紹了
记录小试炼
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
備注:
此處有2000+條qcn,每個qcn里有一個唯一的sn號同樣有個sn_number.txt文件,其中記錄200+個sn號
問題:要求從2000+條qcn中,找出具有sn對應的qcn文件,并將qcn文件以sn號重命名
方法:
用python腳本實現,引入os,shutil模塊
實現方法:
- 遍歷sn_number中的每一個sn號,去判斷sn號是否在2000+條qcn
-
如果不存在
跳過
-
如果存在文件
- #加個判斷:是否文件夾下包含已有的,并以sn命名的qcn
- 判斷 os.path.exists(file)==False
- 重新以sn命名qcn
這里在實現過程中有個問題:
- shutil.move(src, dst) 遞歸的去移動文件,它類似mv命令,其實就是重命名
- 已經匹配qcn,但是shutil.move老是提示權限問題
- 解決方法:我是使用shutil.copy方法,將文件重新copy進行重命名
代碼如下:
import os
, shutil
from os
.path
import *def open_qcn(sn
, path_file
):dirs
= os
.listdir
(path_file
) for file_name
in dirs
: with open(path_file
+ '\\' + file_name
, 'rb') as file_object
: contents
= file_object
.read
().decode
("gbk", 'ignore')if sn
not in contents
: print(sn
+ ' mismatch')continueelse:print(sn
+ ' ' + file_name
)Txt_write
(sn
+ ' ' + file_name
+ '\n',path_file
) nqcn_file
=path_file
+ '\\' + sn
+ '.qcn'if os
.path
.exists
(qcn_file
)==False:shutil
.move
(path_file
+ '\\' + file_name
, qcn_file
)def Txt_write(type,path
): filename
= path
+r
'\Test.txt' file = open(filename
, 'a')file.write
(type) file.close
()
def main():dir_path
= dirname
(abspath
(__file__
))path
= dir_path
+ r
'\1'sn_number
= dir_path
+ '\sn_number.txt'with open(sn_number
, 'r') as file_obj
:while True:line_number
= file_obj
.readline
() if not line_number
:breakelse:open_qcn
(line_number
.strip
(), path
)if __name__
== '__main__':main
()
總結:記錄一下瞎搞的過程,感覺寫的就是一坨,holy shit!
總結
以上是生活随笔為你收集整理的记录小试炼的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。