需求:
- 给定指定的路径,找出*~4mesh.out文件 -->Mesh的相关内容全部放在该路径下面
- 具体格式如下:
-
- StudyName, FilePath, MeshTime, SecondAttempt
实现:
- 该段代码的亮点(心得主要如下)
-
- python在读文件中每一行的时候, 格式如下的:例如“import os\n”,即在一行的末端加上一个换行符
-
- 采取的方法如下:
-
- 将每一行读到一个列表中,同时使用字符串的rstrip()函数,去掉换行符,见行Line34;
- 对列表进行操作,主要是利用查找的方式
- 下一步,将Learning Python一书中有关文件迭代的章节要仔细的看一下
#!/usr/bin/python #File: MeshTime.py #Author: Gene Jiang #Description: importos meshTime = '' status = 0 secondMesh = '' mResult = '' strPath = raw_input("Please enter the path which contains the out file: ") strCSVFile = open("C:\MeshTime.csv", 'w') strHeader = 'StudyName, FilePath, MeshTime, SecondAttempt' strCSVFile.write(strHeader) strCSVFile.write('\n') strCSVFile.close() for root, dirs, files in os.walk(strPath): for f in files: secondMesh = "False" filePath = '' if os.path.splitext(f)[-1] == '.out': meshFileName = os.path.splitext(f)[0] if meshFileName[-4:] == "Mesh": mFile = file(os.path.join(root, f)) filePath = os.path.join(root, f) lines = [line.rstrip() for line in mFile] for i in range(len(lines)): if secondMesh == "False" and lines[i] == "1900132": secondMesh = "True" if lines[i] == "1910001": meshTime = lines[i+5] status = 1 break if status == 1: mResult = f.split("~")[0] + "," + filePath + ',' + meshTime + "," + secondMesh print mResult else: mResult = f.split("~")[0] + "," + filePath + ',' + "Not Finish Analysis, Not Finish Analysis" strCSVFile = open("C:\MeshTime.csv", 'a') strCSVFile.writelines(mResult) strCSVFile.write('\n') strCSVFile.close() print"Done"