为什么我的函数附加文件名字符串而不是文件本身的行?

时间:2019-04-29 14:11:10

标签: python function file

我试图将文件(.py文件)的行添加到列表中,以作为对行进行计数并使用条件语句找出哪些行是代码的一种方式。问题是我创建的函数正在读取“文件名”,而不是文件本身的行。我在哪里错了。我很惊讶,我走了这么远……行之有效,但出于正确的原因。

from tkinter.filedialog import askopenfilename
import time

def getFileName():
    sourceCode = askopenfilename() # Opens dialog box to locate and select file
    return sourceCode

def scLines():
    scList = []
    sourceCode = getFileName()
    for line in sourceCode:
        if line[0] != "#" or line != "":
           scList.append(line)
    return scList

def countscLine():
    lineCount = len(scLines())
    return lineCount

def fCount():
    fList = []
    sourceCode = getFileName()
    for line in sourceCode:
        if line[0:3] == 'def ':
            fAmout.append(line)
    lineCount = len(fList)
    return fList

# Get file name from user
def main():
    print("Select the file to be analyzed")
    time.sleep(5) # Waits 5 seconds before initiating function
    sourceCode = getFileName()
    print("The file is", sourceCode)
    print("The source code has ", countscLine(), "lines of code, and", fCount(), "functions.")
    print(scLines())
    print("")

main()

1 个答案:

答案 0 :(得分:4)

问题是for line in sourceCode:。您实际上需要打开文件。

with open(sourceCode) as f:
    for line in f:
        if line[0] != "#" or line != "":
           scList.append(line)

我建议重命名一些变量,以更清楚地了解它们的实际作用。例如,我将调用sourceCode sourceCodefn或类似名称以表明它是文件名。