python小课文件_[Python]小甲鱼Python视频第028课(文件:因为懂你,所以永恒)课后题及参考解8...
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 8 11:52:02 2019
@author: Administrator
"""
"""
測(cè)試題:
0. 下邊只有一種方式不能打開(kāi)文件,請(qǐng)問(wèn)是哪一種,為什么?
>>> f = open('E:/test.txt', 'w') # A
>>> f = open('E:\test.txt', 'w') # B
>>> f = open('E://test.txt', 'w') # C
>>> f = open('E:\\test.txt', 'w') # D
B不行, 沒(méi)有轉(zhuǎn)義
1. 打開(kāi)一個(gè)文件我們使用open()函數(shù),通過(guò)設(shè)置文件的打開(kāi)模式,決定打開(kāi)的文件具有那些性質(zhì),請(qǐng)問(wèn)默認(rèn)的打開(kāi)模式是什么呢?
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. 請(qǐng)問(wèn) >>> open('E:\\Test.bin', 'xb') 是以什么樣的模式打開(kāi)文件的?
x: create a new file and open it for writing
b: binary mode
3. 盡管Python有所謂的“垃圾回收機(jī)制”,但對(duì)于打開(kāi)了的文件,在不需要用到的時(shí)候我們?nèi)匀恍枰褂胒.close()將文件對(duì)象“關(guān)閉”,這是為什么呢?
只有當(dāng)f的生命周期結(jié)束時(shí),才會(huì)自動(dòng)回收,不然會(huì)一直占用
4. 如何將一個(gè)文件對(duì)象(f)中的數(shù)據(jù)存放進(jìn)列表中?
5. 如何迭代打印出文件對(duì)象(f)中的每一行數(shù)據(jù)?
6. 文件對(duì)象的內(nèi)置方法f.read([size=-1])作用是讀取文件對(duì)象內(nèi)容,size參數(shù)是可選的,那如果設(shè)置了size=10,例如f.read(10),將返回什么內(nèi)容呢?
每次讀10個(gè)字符,不夠10的話按可用字符數(shù)返回
7. 如何獲得文件對(duì)象(f)當(dāng)前文件指針的位置?
f.tell
8. 還是視頻中的那個(gè)演示文件(record.txt),請(qǐng)問(wèn)為何f.seek(45, 0)不會(huì)出錯(cuò),但f.seek(46)就出錯(cuò)了呢?
>>> f.seek(46)
46
>>> f.readline()
Traceback (most recent call last):
File "", line 1, in
f.readline()
UnicodeDecodeError: 'gbk' codec can't decode byte 0xe3 in position 4: illegal multibyte sequence
數(shù)據(jù)編碼無(wú)法解析成有效的字符,gbk編碼下遇到以0xe3開(kāi)頭的字符無(wú)法解析
動(dòng)動(dòng)手:
0. 嘗試將文件( OpenMe.mp3 (700 Bytes, 下載次數(shù): 8062) )打印到屏幕上
1. 編寫(xiě)代碼,將上一題中的文件(OpenMe.mp3)保存為新文件(OpenMe.txt)
"""
#測(cè)試題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------------')
#測(cè)試題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();
#測(cè)試題7
f = open('E:\\test.txt','r')
char_in = f.read(10)
print(f.tell())
f.close();
#動(dòng)動(dòng)手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()
總結(jié)
以上是生活随笔為你收集整理的python小课文件_[Python]小甲鱼Python视频第028课(文件:因为懂你,所以永恒)课后题及参考解8...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: python爬虫提取a标签_Python
- 下一篇: python 实例变量_Python的类