rootPath = arg
pattern = '*.*'
f = open('facad.csv', 'w')
fname = 'facad.csv'
for root, dirs, files in os.walk(rootPath):
for filename in fnmatch.filter(files, pattern):
if 'SETQ' and 'findfile' and 'getvar' in open(os.path.join(root, filename), 'rb').read():
data = os.path.join(root, filename)+", ACAD_LSP\n"
f.write(data)
elif 'base.dcl' in open(os.path.join(root, filename)).read():
data = os.path.join(root, filename)+", ACAD_LSP\n"
f.write(data)
elif 'vl-file-copy' in open(os.path.join(root, filename)).read():
data= os.path.join(root, filename)+", ACAD_LSP\n"
f.write(data)
elif 'FAS4-FILE' in open(os.path.join(root, filename)).read():
data = os.path.join(root, filename)+", ACAD_FAS\n"
f.write(data)
elif 'Autodesk' in open(os.path.join(root, filename)).read():
data = os.path.join(root, filename)+", ACAD_LSP\n"
f.write(data)
elif 'acad.lsp' in open(os.path.join(root, filename)).read():
data = os.path.join(root, filename)+", ACAD_LSP\n"
f.write(data)
f.close()
我收到此错误:
C:\Python33>python D:\python\ftacad.py G:\ginipig\acad_and_lisp\ACAD_samples
Traceback (most recent call last):
File "D:\python\ftacad.py", line 62, in <module>
main()
File "D:\python\ftacad.py", line 40, in main
if 'SETQ' and 'findfile' and 'getvar' in open(os.path.join(root, filename),' rb').read():
TypeError: Type str doesn't support the buffer API
我有各种类型的文件要搜索。 代码不仅在3.x中运行。 在这个版本的Python下运行得很好。
答案 0 :(得分:1)
Python 2.6,2.7,3.x的代码
rootPath = arg
pattern = '*.*'
f = open('facad.csv', 'w')
fname = 'facad.csv'
for root, dirs, files in os.walk(rootPath):
for filename in fnmatch.filter(files, pattern):
fullname = os.path.join(root, filename)
with open(fullname, 'rb') as infile:
data = infile.read()
output = None
if b'SETQ' in data and b'findfile' in data and b'getvar' in data:
output = "ACAD_LSP"
elif b'base.dcl' in data:
output = 'ACAD_LSP'
elif b'vl-file-copy' in data:
output = 'ACAD_LSP'
elif b'FAS4-FILE' in data:
output = 'ACAD_FAS'
elif b'Autodesk' in data:
output = 'ACAD_LSP'
elif b'acad.lsp' in data:
output = 'ACAD_LSP'
if output:
f.write("{0}, {1}\n".format(fullname, output).encode(utf-8'))
f.close()
更短的清晰代码更好。干燥原则:不要重复自己。