Python数据科学基础(七):文件处理

文件处理

    1.文件操作三步走:打开、读写、关闭。

    open(file, mode='r', buffering=-1,encoding=None, errors=None,

    newline=None, closefd=True, opener=None)

  • file参数指定了被打开的文件名称。

  • mode参数指定了打开文件后的处理方式。

  • encoding参数指定对文本进行编码和解码的方式,只适用于文本模式,可以使用Python支持的任何格式,如GBK、utf8、CP936等等。

    2.文件打开模式

  模式

说明

r

读模式(默认模式,可省略),如果文件不存在则抛出异常

w

写模式,如果文件已存在,先清空原有内容

x

写模式,创建新文件,如果文件已存在则抛出异常

a

追加模式,不覆盖文件中原有内容

b

二进制模式(可与其他模式组合使用)

t

文本模式(默认模式,可省略)

+

读、写模式(可与其他模式组合使用)

    3.向文本文件中写入内容,然后再读出。

s = 'Hello world\n文本文件的读取方法\n文本文件的写入方法\n'with open('sample.txt', 'w') as fp:#默认使用cp936编码    fp.write(s)with open('sample.txt') as fp:     #默认使用cp936编码    print(fp.read())

    4.将一个CP936编码格式的文本文件中的内容全部复制到另一个使用UTF8编码的文本文件中。

def fileCopy(src, dst, srcEncoding, dstEncoding):    with open(src, 'r', encoding=srcEncoding) as srcfp:        with open(dst, 'w', encoding=dstEncoding) as dstfp:            dstfp.write(srcfp.read())fileCopy('sample.txt', 'sample_new.txt', 'cp936', 'utf8')

    5.遍历并输出文本文件的所有行内容。

with open('sample.txt') as fp:      #假设文件采用CP936编码    for line in fp:                 #文件对象可以直接迭代        print(line)

    至此,python基础介绍完毕。将以上知识用几个小时过一遍,再来找一些示例自己动手,你会发现python是如此容易入门,后续我们可以利用python做很多有用的事情。尽情期待~

发布了21 篇原创文章 · 获赞 8 · 访问量 6623

猜你喜欢

转载自blog.csdn.net/qq_36936730/article/details/104533637