簡體   English   中英

如何使用腳本遍歷文件夾並寫入文件名?

[英]how do I use my script to iterate over a folder and write the file name?

我編寫了一個腳本,該腳本在日志文件中找到最大值。 然后,我可以將最大值寫入另一個文件。 我的問題是 如何對目錄b中的所有文件運行它。 將“文件名” +“最大值”寫入1個文件。

這是我的代碼:

  1 import re
  2
  3 a = 'NA total MB July.csv'
  4 b = 'Total.csv'
  5
  6 with open(a, 'r') as f1:
  7         with open(b,'w') as f2:
  8                 header = f1.readline()
  9                 data= f1.readlines()
 10                 pattern= re.compile(",|\s")
 11                 maxMB=[]
 12                 for line in data:
 13                         parts = pattern.split(line)
 14                         #print "Log line split",parts #splits the number
 15                         mbCount= parts[2] #index of the number
 16                         mbint=float(mbCount)
 17                         maxMB.append(mbint)# creates a list of all MBs
 18                         #print "MAX: ", maxMB #prints out the max MB
 19                 highest=max(maxMB)
 20                 print highest
 21                 f2.write(str(highest))#writes highest value to file

這是我的文件輸出

167.94

我希望在Total.csv中看到的是

NA total MB July : 167.94
NA total MB August: 123.45
...
..
. For all the csv files with in a folder

無法完全弄清如何一次不處理1個文件並手動更改文件名的方法。 對此n00b的任何幫助將不勝感激。 謝謝!

您可以使用os.listdir()獲取當前目錄中的文件。

files = [f for f in os.listdir('.') if os.path.isfile(f)]
for f in files:
    #do something

您可以以ab模式打開Total.csv文件,以便僅將所有最大值附加到該文件中。

with open('Total.csv', 'ab') as out:
    writer = csv.writer(out, delimiter=',', quotechar='"',quoting=csv.QUOTE_ALL)
    row = (,)
    writer.writerow(row)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM