【问题标题】:Why is my function appending the file name string instead of the lines of the file itself?为什么我的函数附加文件名字符串而不是文件本身的行?
【发布时间】: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 你永远不会打开文件。您只需遍历文件名中的字符。
  • 顺便说一句,为什么不保存文件选择并将文件名用作适当功能的参数?您的程序将要求输入文件名三次,每次可能有人输入不同的名称。
  • 好的...谢谢。我以为这就是我所做的,但仔细观察,每次我调用该函数时,它都会执行……编程需要非常注意细节。感谢您提请我注意。

标签: python function file


【解决方案1】:

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

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

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

【讨论】:

  • :) 你太棒了!!!我想这很简单。适当注意变量。太感谢了! 'with' 函数是我在课堂上还没有学过的东西,所以我必须尝试一下。
  • with 语句(不是函数!)只是打开文件并自动为您进行清理。但是,从概念上讲,您可以将您的 for line in SourceCodeFilename 替换为 for line in open(SourceCodeFilename) [注意更改的变量名称],尽管这实际上可能不会在程序结束之前关闭文件。
  • @RashadJackson 你介意将此解决方案标记为已接受,如果这是你所采用的吗?谢谢。
猜你喜欢
  • 1970-01-01
  • 2011-12-27
  • 1970-01-01
  • 1970-01-01
  • 2012-01-16
  • 2017-04-14
  • 2019-09-23
  • 1970-01-01
  • 2022-12-01
相关资源
最近更新 更多