繁体   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