1

我正在尝试执行以下操作并遇到错误,出了什么问题?

1.根据参数打开目录和子目录中的每个文件

2.检查每个文件的版权信息是否恰好是 3 行

 Copyright (c) 2012 Company, Inc. 
 All Rights Reserved.
 Company Confidential and Proprietary.

编码:

import os
import sys
userstring="Copyright (c) 2012 Company, Inc.\nAll Rights Reserved.\nCompany Confidential and Proprietary."
print len(sys.argv)
print sys.argv[1]
if len(sys.argv) < 2:
    sys.exit('Usage: python.py <build directory>')
for r,d,f in os.walk(sys.argv[1]):
    for files in f:
        with open(os.path.join(r, files), "r") as file:
            if ''.join(file.readlines()[:3]).strip() != userstring:
                print files
4

1 回答 1

1

也许通过改变这些行:

file = open(files, "r")
if userstring not in line:  #check if each file contains the lines
    print file

对这些:

with open(os.path.join(r, files), "r") as file:
    if ''.join(file.readlines()[:3]).strip() != userstring:
        print files

你实现了你的目标。但是当你处理文件时,你应该注意坏文件坏格式和异常处理等等。

于 2012-12-24T20:07:29.230 回答