Discuss / Python / 这章稍微简单了点

这章稍微简单了点

Topic source

with open确实好用简单!廖老师没有讲open的几种模式,我在下面代码有写,有需要的可以看下哈!

__author__ = 'Kaiming'


#P1 打开文件、读文件、关闭文件的典型方法

try:
    f=open('D:/test.txt','r')
    print(f.read())

finally:
    if f:
        f.close()


#P2 推荐的简洁写法,不必显示的关闭文件描述符
#open返回的对象在python中称作file-like 对象,可以是字节流、网络流、自定义流等
with open('D:/test.txt','r') as f:
    #按行读取
    for line in f.readlines():
        print(line.strip())

#P3 直接读取二级制的图片、视频文件

# with open('D:/banner.jpg','rb') as f2:
#     for line in f2.readlines():
#         print(line.strip())


#P4 可以指定编码读取相应的数据,还可以忽略非法编码

with open('D:/test.txt','r',encoding='gbk',errors='ignore') as f3:
    for line in f3.readlines():
        print(line.strip())

#P5 写文件的流程和读文件是一样的 代开文件、写入内容、关闭文件

# 'r'    open for reading (default)
# 'w'    open for writing, truncating the file first
# 'x'    open for exclusive creation, failing if the file already exists
# 'a'    open for writing, appending to the end of the file if it exists
# 'b'    binary mode
# 't'    text mode (default)
# '+'    open a disk file for updating (reading and writing)
# 'U'    universal newlines mode (deprecated)
with open('D:/test12.txt','a+') as f4:
    for line in f4.readlines():
        print(line.strip())
    f4.write('a new line2!')

H_ymin

#2 Created at ... [Delete] [Delete and Lock User]

评论很有帮助!粘下来当作笔记了,嘿嘿。

-292_

#3 Created at ... [Delete] [Delete and Lock User]

想知道w和a有什么区别呢?

w是覆盖,a是续写。

Momentan

#5 Created at ... [Delete] [Delete and Lock User]

readline()读取完了第一行后,可以继续读取第二行吗

廖雪峰

#6 Created at ... [Delete] [Delete and Lock User]

可以,但是注意示例代码是readlines(),可以直接循环得到每一行

黑岩74032

#7 Created at ... [Delete] [Delete and Lock User]

然而大文件如果要处理读取只能while ... readline() 吧

廖雪峰

#8 Created at ... [Delete] [Delete and Lock User]

那要看readlines()返回的是list还是generator,如果是generator,就不会一次性读完

houbo111

#9 Created at ... [Delete] [Delete and Lock User]

好像不好变成generator,变成iterator倒是很好弄


  • 1

Reply