【发布时间】:2019-04-29 14:11:10
【问题描述】:
我正在尝试将文件(.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()
【问题讨论】:
-
在
scLines你永远不会打开文件。您只需遍历文件名中的字符。 -
顺便说一句,为什么不保存文件选择并将文件名用作适当功能的参数?您的程序将要求输入文件名三次,每次可能有人输入不同的名称。
-
好的...谢谢。我以为这就是我所做的,但仔细观察,每次我调用该函数时,它都会执行……编程需要非常注意细节。感谢您提请我注意。