In Python, how can I open a file and read it on one line, and still be able to close the file afterwards?

前端 未结 7 2113
面向向阳花
面向向阳花 2021-02-10 07:26

While working through this exercise I ran into a problem.

from sys import argv
from os.path import exists

script, from_file, to_file = argv
print \"Copying from         


        
7条回答
  •  隐瞒了意图╮
    2021-02-10 07:59

    You should think of this as an exercise to understand that input is just a name for what open returns rather than as advice that you ought to do it the shorter way.

    As other answers mention, in this particular case the problem you've correctly identified isn't that much of an issue - your script closes fairly quickly, so any files you open will get closed fairly quickly. But that isn't always the case, and the usual way of guaranteeing that a file will close once you're done with it is to use a with statement - which you will find out about as you continue with Python.

提交回复
热议问题