简体   繁体   English

将文件作为函数参数传递

[英]Passing a file as a function argument

If I have a text file ( sequencedata.txt ) in a directory named documents: 如果我在名为documents的目录中有一个文本文件( sequencedata.txt ):

/~/documents/sequencedata.txt

How would I define a function named sequenceinfo that would count the number of entries that start with # in the file of above pathway and return this count with the syntax "there are * entries" , in which the * is the counted number of entries? 如何定义一个名为sequenceinfo的函数,该函数将计算上述途径文件中以#开头的条目数,并使用语法"there are * entries"返回此计数,其中*是计数的条目数?

What I have so far: 到目前为止我所拥有的:

#!/usr/bin/python
def sequenceinfo(sequencedata):
    my_file = open("/~/documents/sequencedata.txt")
    my_dna = my_file.read()
    ecoliseq = my_dna.count('#')
    return ecoliseq

print("There are " + str(ecoliseq) + " sequences")

There are a few things here: 这里有几件事:

  1. The name ecoliseq is not visible outside of the function sequenceinfo . ecoliseq这个名称在函数sequenceinfo之外是不可见的。 Consequentially, the print line will raise a NameError because Python will be unable to find ecoliseq . 因此, print行会引发NameError因为Python将无法找到ecoliseq However, ecoliseq is returned by the function, which means that you can access its value by calling the function and then printing the result. 但是, ecoliseq由函数返回,这意味着您可以通过调用函数然后打印结果来访问其值。

  2. You made sequenceinfo take an argument that is never used. 你使sequenceinfo采用了一个从未使用过的参数。 Is this supposed to be the path to the file? 这应该是文件的路径吗? I'm going to assume that it is, but you should remove it if not. 我会假设它是,但如果没有,你应该删除它。

  3. Not a major problem, but you are not closing the file when you are done with it. 这不是一个主要问题,但是当你完成它时你并没有关闭文件。 You should always manage and properly release the resources that your program aquires. 您应始终管理并正确释放程序所需的资源。 The easiest way to do this with files is to use a with-statement to open them, which will automatically close them for you. 使用文件执行此操作的最简单方法是使用with语句打开它们,这将自动为您关闭它们。

In all, your code should look something like the following: 总之,您的代码应如下所示:

#!/usr/bin/python
def sequenceinfo(path):
    with open(path) as my_file:
        my_dna = my_file.read()
    ecoliseq = my_dna.count('#')
    return ecoliseq

print("There are " + str(sequenceinfo("/~/documents/sequencedata.txt")) + " sequences")

Also, there may be a fourth problem in that my_dna.count('#') will return the count of every # in the file. 另外,可能存在第四个问题,即my_dna.count('#')将返回文件中每个 #的计数。 But you said in your question that you only want to count the entries that start with # . 但是你在问题中说过你只想计算以#开头的条目。 You will need to fix this bug if so. 如果是这样,您将需要修复此错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM