python-文件操作

1. python-文件操作

1.1 open函数

​ 要想读取文件(如txt、csv等),第一步要用open()内建函数打开文件,它会返回一个文件对象,这个对象拥有read()、write()、close()等方法。

  • 语法格式

    open(file,mode='r',encoding=None)
    
  • file: 打开的文件路径

  • mode(可选):打开文件的模式,如只读、追加、写入等

    • r:只读

    • w:只写

    • a:在原有内容的基础上追加内容(末尾)

    • w+:读写

      如果需要以字节(二进制)形式读取文件,只需要在mode值追加‘b’即可,例如wb

1.2 文件对象操作

  • 语法格式

    f = open('test.txt')
    
  • 使用命令解析

    方法 描述
    f.read([size]) 读取size字节,当未指定或给负值时,读取剩余所有的字节,作为字符串返回
    f.readline([size]) 从文件中读取下一行,作为字符串返回。如果指定size则返回size字节
    f.readlines([size]) 读取size字节,当未指定或给负值时,读取剩余所有的字节,作为列表返回
    f.write(str)
    f.flush
    写字符串到文件
    刷新缓冲区到磁盘
    f.seek(offset[, whence=0]) 在文件中移动指针,从whence(0代表文件起始位置,默认。1代表当前位置。2代表文件末尾)偏移offset个字节
    f.tell() 当前文件中的位置(指针)
    f.close() 关闭文件
    .strip() strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。 注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。
    .split() Python split() 通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则分隔 num+1 个子字符串
  • 示例:遍历打印每一行

    f = open('computer.txt')
    for line in f:
    	print(line.strip(‘\n’)) # 去掉换行符
    

1.3 with语句

  • with语句:不管在处理文件过程中是否发生异常,都能保证with 语句执行完毕后已经关闭了打开的文件句柄。

  • 示例:

    with open("computer.txt",encoding="utf8") as f:
    	data = f.read()
    	print(data)
    

2. 案例

2.1 文件读取的基本操作

#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# Author:shichao
# File: .py

f = open("/tmp/hello.txt",mode='r',encoding='utf-8')

result = f.read()            # 读取所有内容
result = f.readline()        # 读取一行数据
result = f.readlines()        # 读取所有内容返回一个列表

print(result)

f.close()            # 关闭文件

2.2 使用with语句进行文件读取

#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# Author:shichao
# File: .py

# 使用with读取文件
with open("/tmp/hello.txt",encoding="utf8") as f:
	data = f.read()
	print(data)

2.3 使用with语句进行文件读取去除首尾空格和换行符

#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# Author:shichao
# File: .py

# 使用with读取文件
with open("./hello.txt", encoding="utf8") as f:
	data = f.read().strip()  # 去除首尾空格和换行符
	print(data)

2.4 使用with语句进行文件读取去除首尾空格和换行符,并指定分隔符对字符串进行切片

#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# Author:shichao
# File: .py

# 使用with读取文件
with open("./hello.txt", encoding="utf8") as f:
	data = f.read().strip().split()  # 指定分隔符对字符串进行切片 
	print(data)
posted @ 2022-12-26 11:46  七月流星雨  阅读(74)  评论(0编辑  收藏  举报