简体   繁体   English

如何使用脚本遍历文件夹并写入文件名?

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

I wrote a script that finds the maximum value in a log file. 我编写了一个脚本,该脚本在日志文件中找到最大值。 I can then write the max value to another file. 然后,我可以将最大值写入另一个文件。 My problem: a. 我的问题是 is how do I run it against all the files in a directory b. 如何对目录b中的所有文件运行它。 write "Filename" + "Max Value" into 1 file. 将“文件名” +“最大值”写入1个文件。

here's my code: 这是我的代码:

  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

Here's my files output 这是我的文件输出

167.94 167.94

What I'm looking to see in Total.csv is 我希望在Total.csv中看到的是

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

Can't quite figure out how to make this work without processing 1 file at a time and manually changing the file name. 无法完全弄清如何一次不处理1个文件并手动更改文件名的方法。 Any help to this n00b would be greatly appreciated. 对此n00b的任何帮助将不胜感激。 THANKS! 谢谢!

You can use os.listdir() to grab files in current directory. 您可以使用os.listdir()获取当前目录中的文件。

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

You can open Total.csv file in ab mode so that you can append all the max values into that one file only. 您可以以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