After-school exercises for small turtle files

2016.12.17

 

Homework questions about documents.


 The answer is B, B cannot open the file.

1. To open a file, we use the open() function to determine the properties of the opened file by setting the open mode of the file. What is the default open mode?

A: The default open mode of the open() function is 'rt', which means that it is readable and the text mode is open.

2. What mode does >>>open('E:\\Test.bin','xb') open the file in?

A: Open "E:\\Test.bin" in "Writable and Binary Mode".

It should be noted here that both 'x' and 'w' open files in "writable" mode, but when 'x' mode is opened, if the same file name already exists in the path, an exception will be thrown, and 'w' mode will directly overwrite the file with the same name.

3. Although Python has a so-called "garbage collection mechanism", we still need to use f.close to "close" the opened file when it is not needed. Why?

Answer: Python has a garbage collection mechanism that automatically closes the file when the reference count of the file object reaches zero, so in Python programming, if you forget to close the file, it will not cause a memory leak as dangerous.

4. How to store the data in a file object (f) into a list.

Answer: list(f)

5. How to print out each line of data in the file object (f) iteratively.

Just use the for loop to iterate over the file objects

for each_line in f:

     print(each_line)

6. The built-in method f.read(size=-1) of the file object is used to read the content of the file object. The size parameter is optional. If size=10 is set, such as: f.read(10), the What kind of content is returned.

A: Will return 10 characters from the file start pointer.

7. Try printing the file (OpenMe.mp3) to the screen

A: You can open it directly in the form of a text document.

f = open('OpenMe.mp3')

for each_line in f:

       print(each_line,end='')

f.close()

8. Write the code to save the file (OpenMe.mp3) in the previous question as (OpenMe.txt)

f1=open('OpenMe.mp3')

f2=open('OpenMe.txt','x')

f2.write(f1.read())

f2.close()

f1.close()

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326943713&siteId=291194637