[Python]小甲鱼Python视频第028课(文件:因为懂你,所以永恒)课后题及参考解8

# -*- coding: utf-8 -*-
"""
Created on Fri Mar  8 11:52:02 2019

@author: Administrator
"""
                                                  
"""

测试题:

0. 下边只有一种方式不能打开文件,请问是哪一种,为什么?

>>> f = open('E:/test.txt', 'w')   # A
>>> f = open('E:	est.txt', 'w')   # B
>>> f = open('E://test.txt', 'w')  # C
>>> f = open('E:\test.txt', 'w')  # D


B不行, 没有转义


1. 打开一个文件我们使用open()函数,通过设置文件的打开模式,决定打开的文件具有那些性质,请问默认的打开模式是什么呢?

help(open)

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
 'r'       open for reading (default)
 't'       text mode (default)


2. 请问 >>> open('E:\Test.bin', 'xb') 是以什么样的模式打开文件的?
    x: create a new file and open it for writing
    b: binary mode

3. 尽管Python有所谓的“垃圾回收机制”,但对于打开了的文件,在不需要用到的时候我们仍然需要使用f.close()将文件对象“关闭”,这是为什么呢?
    只有当f的生命周期结束时,才会自动回收,不然会一直占用
    
4. 如何将一个文件对象(f)中的数据存放进列表中?

5. 如何迭代打印出文件对象(f)中的每一行数据?

6. 文件对象的内置方法f.read([size=-1])作用是读取文件对象内容,size参数是可选的,那如果设置了size=10,例如f.read(10),将返回什么内容呢?
    每次读10个字符,不够10的话按可用字符数返回
    
7. 如何获得文件对象(f)当前文件指针的位置?
    f.tell    
    
8. 还是视频中的那个演示文件(record.txt),请问为何f.seek(45, 0)不会出错,但f.seek(46)就出错了呢?
>>> f.seek(46)
46
>>> f.readline()
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    f.readline()
UnicodeDecodeError: 'gbk' codec can't decode byte 0xe3 in position 4: illegal multibyte sequence

数据编码无法解析成有效的字符,gbk编码下遇到以0xe3开头的字符无法解析

动动手:
0. 尝试将文件(  OpenMe.mp3 (700 Bytes, 下载次数: 8062) )打印到屏幕上
1. 编写代码,将上一题中的文件(OpenMe.mp3)保存为新文件(OpenMe.txt)
    
"""


#测试题4
f = open('E:\test.txt','r');
context_list1 = list(f)
f.seek(0,0)
context_list2 = list();

while True:
        char_in = f.read(1);
        if char_in == '':
            break;
        else:
            context_list2.append(char_in);
f.close()
print('1------------')
print(context_list1)  
print('2------------')
print(context_list2)
print('3------------')


#测试题5.
f = open('E:\test.txt','r');
context_list = list();
filelines = f.readlines();
print('1------------')
for each in filelines:
    print(each)
print('2------------')
f.seek(0,0)
for each in f:
    print(each)
print('3------------')
f.close();  

#测试题7
f = open('E:\test.txt','r')
char_in = f.read(10)
print(f.tell())
f.close();

#动动手0&1
f_in  = open('E:\OpenMe.mp3','r');
f_out = open('E:\OpenMe.txt','w');

for each in f_in:
    print(each)
    f_out.writelines(each)
    
f_in.close()
f_out.close()

        

  

~不再更新,都不让我写公式,博客园太拉胯了
原文地址:https://www.cnblogs.com/alimy/p/10502995.html