Why truncate when we open a file in 'w' mode in python

前端 未结 8 2125
再見小時候
再見小時候 2020-12-13 05:40

I am going through Zed Shaw\'s Python Book. I am currently working on the opening and reading files chapters. I am wondering why we need to do a truncate, when we are alread

8条回答
  •  悲&欢浪女
    2020-12-13 06:21

    If you would READ the questions before asking it, he answers it for you:

    Extra Credit: " If you feel you do not understand this, go back through and use the comment trick to get it squared away in your mind. One simple English comment above each line will help you understand, or at least let you know what you need to research more.

    Write a script similar to the last exercise that uses read and argv to read the file you just created.

    There's too much repetition in this file. Use strings, formats, and escapes to print out line1, line2, and line3 with just one target.write() command instead of 6.

    Find out why we had to pass a 'w' as an extra parameter to open. Hint: open tries to be safe by making you explicitly say you want to write a file.

    If you open the file with 'w' mode, then do you really need the target.truncate()?

    Go read the docs for Python's open function and see if that's true." - Zed Shaw.

    He explicitly wants you to find these things out for yourself, this is why his extra credit is important.

    He also EXPLICITLY states that he wants you to PAY ATTENTION TO DETAIL. Every little thing matters.

提交回复
热议问题