不好意思我是来搬砖的,转自:http://www.jb51.net/article/119907.htm
我们先创建一个.txt文件,比如我创建的就是readline.txt,输入以下内容:
Hello,line1
Welcome,line2
I am fine,line3
一、 read(size)方法
从文件中读取size个字节,如果不设置size参数,表示全部读取,该方法返回的是字符串格式
① 不设置size参数
code:
with open("readline.txt") as f: lines = f.read() print(lines) print(type(lines))# 输出字符串类型 f.close()
output:
Hello,line1
Welcome,line2
I am fine,line3
<class 'str'>
② 设置size参数
code:
with open("readline.txt") as f: lines = f.read(5) print(lines) print(type(lines))# 输出字符串类型 f.close()
output:
Hello
<class 'str'>
二、readline()方法
该方法每次读取一行,所以占用内存较小,适合大文件,该方法返回字符串格式
① 不设置循环的话只能读取一行
code:
with open("readline.txt") as f: lines = f.readline() print(type(lines)) print(lines)# 这样子这只能读取一行,全部读取需要使用循环读取 f.close()
output:
<class 'str'>
Hello,line1
② 设置循环全部读取
code:
with open("readline.txt") as f: line = f.readline() print(type(line)) # 设置循环的也很巧妙,只要那行还有内容(包括空格)都要读取 while line: print(line) line = f.readline() f.close()
output:
<class 'str'>
Hello,line1
Welcome,line2
I am fine,line3
三、readlines()方法
读取所有行的内容,保存在一个列表中,每一行作为列表中的一个元素,最后返回这个列表,读取大文件比较占内存
with open("readline.txt") as f: lines = f.readlines() print(type(lines)) print(lines) f.close() for line in lines: print(line)
output:
<class 'list'>
['Hello,line1\n', 'Welcome,line2\n', 'I am fine,line3\n']
Hello,line1
Welcome,line2
I am fine,line3
四、增加一点点skill
上面的输出我们会看到每个列表的元素中末尾都会有一个"\n",这是由于换行的时候产生的,在很多分类任务中,如下txt,但是我们需要文件中将每一类变成列表的每一个元素,不希望存在"\n"
code:
import os path = "model_data/classify.txt" classes_path = os.path.expanduser(path) # print(path) # print(classes_path) with open(classes_path) as f: class_names = f.readlines() print(class_names) class_names = [c.strip() for c in class_names] print(class_names)
output:
['person\n', 'car\n', 'dog\n', 'cat\n', 'monkey']
['person', 'car', 'dog', 'cat', 'monkey']
Tip(参考):Python strip() 方法用于移除字符串头尾指定的字符,当参数为空的时候,两端的空白符,\r,\n,\t都被删除了,但是中间的那个空白符没动
更多python读取txt文件进行简单处理例子可以参考另一篇博客学习笔记
转自:http://www.jb51.net/article/119907.htm
strip()参考:https://blog.csdn.net/csdn15698845876/article/details/73469234
The end.
最后附一个split()函数(与前面无关):
我老是忘记的就是该函数返回的是列表,按照括号内设置格式分开的每一部分作为列表的每一个元素
>>> a = "abc,def,ghi"
>>> a
'abc,def,ghi'
>>> a.split(",")
['abc', 'def', 'ghi']
The end_2.