关于python:ValueError:关闭文件的I / O操作。

ValueError: I/O operation on closed file.

有人能帮我一下吗?我运行文件时出错了值错误:对已关闭文件执行I/O操作。我只是想运行一个模拟测试文件一二三四五六七八九十

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
def main():
# Declare variables
line = ''
counter = 0

# Prompt for file name
fileName = input('Enter the name of the file: ')

# Open the specified file for reading
infile = open(fileName, 'r')

# Priming read
line = infile.readline()
counter = 1

# Read in and display first five lines
while line != '' and counter <= 5:
# Strip '
'
    line = line.rstrip('

')
    print(line)
    line = infile.readline()
    # Update counter when line is read
    counter +=1  

# Close file
    infile.close()

# Call the main function.
main()


在Python中,缩进是语法的一部分——它表示代码块。

您的代码片段清楚地显示了infile.close()操作在一个循环中,所以它是在第一次迭代中执行的。因此,第二次从文件读取失败,因为文件已在上一次迭代中关闭。

只需固定线infile.close()

或者,使用上下文管理器来允许Python管理资源清理。

1
2
3
4
with open(fileName, 'r') as infile:
    pass  # operate on file here

# file will be closed automatically when you leave code block above.