程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python extracts the specified content in the file and copies it to another file

編輯:Python
Now there are many different names txt Type file In every file Another sentence with the same content I want to extract and add this before this sentence txt Folder name

for example A Folder has log.txt file
B Folder has log.txt file
C Folder has log.txt file
Every log.txt There is result=89
Need to put log.txt in result=89 Copy to a specified file And add the folder name in front A result=89 such
The result in the new file is Here's how
A result=89
B result=89
C result=89

If you can solve it, you can pay another fee

Operation results and error reporting contents
My solution ideas and tried methods
What I want to achieve



Take the answer :
import ospath=r'C:\Users\85949\Desktop\total'dirs=os.listdir(path) # Read the secondary directory under the primary directory bc=open(" Last .txt",'w+',encoding='utf-8') # To save last txtfor odirs in dirs: edir=os.path.join(path,odirs) # Splice the primary directory with the folder name under the directory ( Get the absolute path of the folder ) edirs=os.listdir(edir) # Read the files in the folder  for file in edirs: files=os.path.join(edir,file) # Splice the path of the folder with the file name under the folder ( Get the absolute path of the file ) a=open(files,'r') for b in a.readlines(): c=b.strip('\n') # Delete the newline character of the traversal line  if 'pos close'in c: bc.write(odirs + ' ' + c + '\n') elif 'POS CLOSE' in c: # Judge whether this line has “pos close” character  bc.write(odirs+' '+c+'\n')bc.close()


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved