Python 中File I/O 和一些常用的方法

简介:

version:Python 3.3.2

Python用open()返回一个文件,最常用的open函数是open(filename , mode)

其中,mode包括有"w"(write), “r”(read) , “a”(open the file for appending), 当然也可以用“wt”表示写入text,“rt”表示读取text;

file.readline()可以一次读取文件中内容的一行

* 每次文件操作完成之后,一定要加上file.close()函数将文件关闭。

>>> strings = """\I'm a great man who was born in China
I was born to give and give and give
This is a new line
And this is another new line"""
>>> file.write(strings)
123                  #此处表示写入的内容总共有多少byte
>>> file.close()

我们可以调用read()函数将文件的内容打印出来,但是当read()之后,当前的位置将停留在末尾也就是文字的最后位置,如果这时候想再次打印文件内容,调用read()函数将得到空的内容,可行的办法之一是将文件关闭再重新打开,当然我们也有一些新的办法来简化此操作。

 
 
>>> file = open("output.txt","rt")
>>> print(file.read())
\I'm a great man who was born in China
I was born to give and give and give
This is a new line
And this is another new line
>>> print(file.read())
#这里将会是空白,因为此刻指针(光标)的位置处于段落末尾
 
 
 

1. seek()

seek可以用来改变当前object的位置(例如file read之后),通常的格式seek(offset, from_what)。

The position is computed from adding offset to a reference point; the reference point is selected by the from_what argument. A from_what value of 0 measures from the beginning of the file, 1 uses the current file position, and 2 uses the end of the file as the reference point. from_what can be omitted and defaults to 0, using the beginning of the file as the reference point.

默认只有一个参数,就表示从文件开始的位置(0),因此,seek(0)就表示目前是处于文件的开头,第二个参数表示从哪里开始计算,0表示开头,也是默认的,1表示当前位置,2表示末尾。

>>> file.seek(0)
0#当前位置
>>> print(file.read())
\I'm a great man who was born in China
I was born to give and give and give
This is a new line
And this is another new line

2. 利用list,将file中的文字存入到list中
file有一个函数readlines(),注意此函数和readline()有区别,readline是一次读取一行,而readlines()是将所有数据存入list中,每一行作为list的一个element,如此之后,即便我们close的文件,依旧可以继续打印文件里已经存储在list中的内容了。
>>> x = file.readlines()#错误,注意此时的位置已经处于末尾了
>>> print(x)
[]#所以打印出来的内容为空
>>> print(x[0])
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    print(x[0])
IndexError: list index out of range
>>> file.seek(0)#将位置置于开头
0
>>> x = file.readlines()
>>> print(x)
["\\I'm a great man who was born in China\n", 'I was born to give and give and give\n', 'This is a new line\n', 'And this is another new line']
>>> print(x[0])#打印list的各项内容
\I'm a great man who was born in China
	
>>> file.close()#即便关闭了file,也可以继续操作,因为内容已经存储到了list中

>>> print(x[0])
\I'm a great man who was born in China

>>> print(x[3])
And this is another new line
>>> 
代码中我犯了一个错误,第一次没有将位置seek到开头,所以第一次没有将lines存入到x中,也就是说,若想把每一行存入到list中,也需要将当前位置置于0
目录
相关文章
|
1天前
|
测试技术 开发者 Python
Python检查函数和方法的输入/输出
【5月更文挑战第5天】Python检查函数和方法的输入/输出
9 1
|
2天前
|
SQL 关系型数据库 数据库连接
使用 Python 访问数据库的基本方法
【5月更文挑战第12天】在Python中操作数据库涉及安装数据库驱动(如mysql-connector-python, psycopg2, pymongo)、连接数据库、执行查询/更新、处理结果集及关闭连接。使用ORM(如SQLAlchemy)可简化操作。通过上下文管理器(with语句)能更好地管理资源和错误。注意根据实际需求处理事务、错误和安全性,例如使用SSL连接。
13 2
|
3天前
|
Python
【Python进阶(二)】——程序调试方法
【Python进阶(二)】——程序调试方法
|
5天前
|
存储 Linux Shell
python移除/删除非空文件夹/目录的最有效方法是什么?
python移除/删除非空文件夹/目录的最有效方法是什么?
9 0
|
7天前
|
Python
【Python 基础】Python中的实例方法、静态方法和类方法有什么区别?
【5月更文挑战第6天】【Python 基础】Python中的实例方法、静态方法和类方法有什么区别?
|
7天前
|
数据处理 Python
Python中每个字段增加多条数据的高效方法
Python中每个字段增加多条数据的高效方法
14 1
|
8天前
|
存储 数据挖掘 Python
Python技术分享:实现选择文件或目录路径的方法
Python技术分享:实现选择文件或目录路径的方法
17 2
|
8天前
|
数据处理 Python
Python中按指定数量分割列表字符串的方法
Python中按指定数量分割列表字符串的方法
9 1
|
12天前
|
Python
使用Python pandas的sort_values()方法可按一个或多个列对DataFrame排序
【5月更文挑战第2天】使用Python pandas的sort_values()方法可按一个或多个列对DataFrame排序。示例代码展示了如何按'Name'和'Age'列排序 DataFrame。先按'Name'排序,再按'Age'排序。sort_values()的by参数接受列名列表,ascending参数控制排序顺序(默认升序),inplace参数决定是否直接修改原DataFrame。
25 1
|
13天前
|
机器学习/深度学习 数据可视化 前端开发
【Python机器学习专栏】机器学习模型评估的实用方法
【4月更文挑战第30天】本文介绍了机器学习模型评估的关键方法,包括评估指标(如准确率、精确率、召回率、F1分数、MSE、RMSE、MAE及ROC曲线)和交叉验证技术(如K折交叉验证、留一交叉验证、自助法)。混淆矩阵提供了一种可视化分类模型性能的方式,而Python的scikit-learn库则方便实现这些评估。选择适合的指标和验证方法能有效优化模型性能。