作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我写了一个小模块,它将在一个目录及其所有子目录中的文件中搜索某个输入字符串的出现。几次都很方便,如果我记得我用过的一些函数/变量名称,主要是为了查找旧脚本。
所以,前几天,当我使用这些功能时,我完全感到困惑,并开始从坐在我 table 另一边的耳机中非常微弱地听到重复的哔哔声。起初我以为是有人的电话响了。但不,Python 是通过摩尔斯电码与我交流的。
我不知道为什么会这样。我一直在继续运行这些功能并发出哔哔声,但并不总是以相同的模式。这些函数只打开具有读取权限的文件。代码就是这样:
import os
import glob
def directory_crawl_for_string(dir_name, string, ofile):
"""Crawl dir_name and all of its subdirectories, opening files and
checking for the presence of a string"""
#get input directory's listings
dir_contents = glob.glob(dir_name)
#loop over the listings
for dir_element in dir_contents:
if(os.path.isfile(dir_element)):
#read the file, checking for the string
check_for_string(dir_element, string, ofile)
else:
if(os.path.isdir(dir_element)):
directory_crawl_for_string(dir_element + '\\*', string, ofile)
def check_for_string(dir_element, string, ofile):
try:
ifile = open(dir_element, 'r')
except IOError as e:
pass
else:
count = 1
for line in ifile:
if(string in line.lower()):
print count,line,dir_element
ofile.write('%s,%d,%s' % (dir_element, count, line))
count += 1
ifile.close()
def init_crawl(start_dir, string, output_dir):
"""args:
start_dir - directory to start the crawl at
string - string to search for
output_dir - directory to write output text file inside of"""
if(output_dir):
fn = output_dir.rstrip('/').rstrip('\\') + '/dirs.txt'
else:
fn = 'dirs.txt'
ofile = open(fn, 'w')
ofile.write('file path,line number of occurance of "%s",exact line\n' % string)
directory_crawl_for_string(start_dir, string, ofile)
ofile.close()
print('list of files containing "%s" written to "%s"' % (string, fn))
要启动它,您需要向 init_crawl()
传递要从中向下爬行的目录、要搜索的字符串以及要将输出文本文件写入其中的目录。例如:init_crawl(r'C:\directory-to-crawl', 'foo', r'C:\output-directory')
我什至不知道要问什么具体问题,但为什么会这样?我可以看出,当函数尝试读取 PDF 和电子表格等非文本文件时,通常会发出哔哔声。有时终端也会死机...
输出只是一个 csv,其中包含找到字符串的文件路径、行号和包含字符串的行。
最佳答案
这一行:
print count,line,dir_element
可能正在打印 BEL character如果您提供程序二进制文件。
为了测试,这里是我写的一小段代码。 Python 会尝试一个一个地播放它。不用担心。开心点:)
def bel(): return chr(7)
def wait(duration): return chr(0) * (duration*1000000)
song = ''
for _ in range(5):
song += bel()
song += wait(1)
song += bel()
song += wait(1)
song += bel()
song += wait(5)
print song
关于python - 为什么用于读取文件的 Python 脚本会导致我的计算机发出哔哔声?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38313445/
我是一名优秀的程序员,十分优秀!