【问题标题】:Why my python code is showing value error?为什么我的 python 代码显示值错误?
【发布时间】:2020-12-14 21:26:10
【问题描述】:

我正在编写这个 python 代码来检查 DNA 序列文件。输出将是与此 DNA 匹配的人的姓名。 这个链接有分配的描述。 https://cs50.harvard.edu/x/2020/psets/6/dna/ 但是当我尝试运行代码时,它的显示值错误。

请有人告诉我代码中的错误。 我是编程新手。

from sys import argv, exit
import csv

def max_Reptitions_of_substrings(dnaSequences , substring):
 arr = [0] * len(dnaSequences)
 for i in range(len(dnaSequences) - len(substring), -1, -1):
     if dnaSequences[i: i + len(substring)] == substring:
       if i + len(substring) > len(dnaSequences) - 1:
           arr[i] = 1
       else:
           arr[i] = 1 + arr[i + len(substring)]
 return max(arr)

def print_Matching(reading, newdata):
    for i in reading:
        human = i[0]
        value = [int(digit) for digit in i[1:]]
        if value == newdata:
         print(human)
         return
    print("No match")


def main():
  if len(argv) != 3:
      print("Missing Command line Argument")
      exit(1)
  
with open(argv[1], 'r') as database:
       reading = csv.reader(database)
       sequences = next(reading)[1:]
   
with open(argv[2], 'r') as sequenceFilestrong text:
    dnaSequences = sequenceFile.read() 
    newdata = [max_Reptitions_of_substrings(dnaSequences, substr) for substr in sequences]
    print_Matching(reading, newdata)


显示的值错误为


Traceback (most recent call last):
  File "dna.py", line 36, in <module>
    print_Matching(reading, newdata)
  File "dna.py", line 15, in print_Matching
    for i in reading:
ValueError: I/O operation on closed file.

【问题讨论】:

    标签: python python-3.x file indentation valueerror


    【解决方案1】:
    with open(argv[1], 'r') as database:
           reading = csv.reader(database)
           sequences = next(reading)[1:]
    

    此代码块显示 csv 阅读器已关闭。

    【讨论】:

      【解决方案2】:

      错误信息非常明确且准确:

      ValueError: 对已关闭文件的 I/O 操作。

      您正在with 块中打开您的 CSV 文件,并基于该文件创建一个新的 CSV 阅读器。但是在with 块的末尾,文件被关闭。 reading 现在指的是链接到已关闭文件连接的 CSV 阅读器。

      因此错误。

      【讨论】:

        【解决方案3】:

        尝试查看代码缩进,这在 Python 中非常重要。第一个 with 应该在 function main 内,第二个 with 应该在第一个 with 内。 为什么? 只看代码。在打印匹配中,您正在使用 reading csv.reader,它现在尝试使用已关闭的文件作为参数传递。

        【讨论】:

        • 感谢 Macialek 您的提示解决了我的问题
        猜你喜欢
        • 2019-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-27
        • 1970-01-01
        • 2014-10-22
        相关资源
        最近更新 更多