数“某物”在一个文件夹中的多个文本文件中
我正在尝试计算文件中出现“Tmp”的次数以及该计数属于哪个文件。我创建了一个可以运行的脚本,但我必须为每个文件设置输入文件和输出目录。为了改进它,我希望脚本在设置一次后遍历文件夹中的每个文件。
我一直在试验:
import tkFileDialog
import glob
import os
directory = tkFileDialog.askdirectory()
for infile in glob.glob(os.path.join(directory, "*.*")):
open(infile, "r").read()
infile.count("Tmp")
当前我正在计算“Tmp”出现在文件名中而不是实际文件中的次数,当我键入时:
print infile
它输出文本文件的内容而不是目录?我只是对去哪里或做什么感到困惑。
I am trying to count the number times "Tmp" occurs in a file and what file the count belongs to. I created a script that works but I have to setup the input file and output directory for each file. To improve it I would like the script to go through each file in a folder after setting it up once.
I have been experimenting with:
import tkFileDialog
import glob
import os
directory = tkFileDialog.askdirectory()
for infile in glob.glob(os.path.join(directory, "*.*")):
open(infile, "r").read()
infile.count("Tmp")
Currently I am counting the number of times "Tmp" occurs in the file name and not the actual file, when I type:
print infile
it outputs the contents of the text files but not the directory? I am just confused on where to go or what to do.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会使用 os.walk 而不是 glob:
I would use os.walk rather than glob:
那应该是:
That should be: