說明:有段時間需要讀取上百個文件的單點能(sp),就寫了下面的代碼(計算化學狗努力轉行中^-^)
import os.path
import re
# 1 遍歷指定目錄,顯示目錄下的所有文件名
def each_file(file_path):
path_dir = os.listdir(file_path)
# 將得到列表內的文件排序(因為自己要讀取的文件類型是1.out,2.out,3.out......這樣的,所以可以切片排序)
path_dir.sort(key = lambda x: x.split('.'[0]))
for one_dir in path_dir:
print(one_dir)
one_dir_path = os.path.join('%s/%s' % (file_path, one_dir))
if os.path.isfile(one_dir_path):
read_file(one_dir_path)
continue
each_file(one_dir_path)
# 2 匹配出所需的內容,並寫入指定文檔
def read_file(filename):
fopen = open(filename, 'r')
fwrite = open("sp.txt", 'a')
file_read = fopen.read()
ret = re.findall(r"\\(HF=.+?)\\", file_read)
if not ret:
fwrite.write(filename + "計算結果有誤" + "\n")
for sp in ret:
fwrite.write(filename + sp + "\n")
fwrite.close()
fopen.close()
if __name__ == "__main__":
# 清除sp.txt內存在的內容
if os.path.exists('/home/python/Desktop/rw/sp.txt'): # 此路徑為存放此段代碼的目錄
fwrite = open("sp.txt", 'w')
fwrite.truncate()
filenames = input("請輸入文件的絕對路徑:")
each_file(filenames)
