Python 程序不需要引入特殊的模块,即可以处理文件。
文件对象包括基本函数和处理文件所需要的各种方法,操作非常简单。
读取文本文件的方法,包括 read(),readline() 和 readlines(),
- read([长度]) : 返回指定长度数量的字符,如果省略参数,则读取全部内容
- readline() : 返回下一行数据
- readlines() : 读取全部文件行到数组列表
读取整个文件内容
with open("my_file.txt", "r") as my_file:
str = my_file.read()
print(str)
只读取一行
with open("my_file.txt", "r") as my_file:
str = my_file.readline()
print(str)
使用长度读取数据
with open("my_file.txt", "r") as my_file:
str = my_file.read(38) #按长度读取文件
print(str)
将全部行读取到数组里面
with open("my_file.txt", "r") as my_file:
str = my_file.readlines()
print(str)
按行读文件
如果想较快的读取文件的所有行,可以使用循环。
with open("my_file.txt", "r") as my_file:
for line in my_file:
print(line)
文件位置
Python 的 tell() 方法
tell() 返回文件的当前读写位置。
with open("my_file.txt", "r") as my_file:
str = my_file.readline()
print(str) # 获得当前文件读位置
pnt = my_file.tell()
print(pnt)
Python 的 seek() 方法
seek() 方法可以按偏移量设定文件当前位置。
with open("my_file.txt", "r") as my_file:
my_file.seek(20)
str = my_file.readline()
print(str) # 将文件游标放在初始位置
my_file.seek(0)
str = my_file.readline()
print(str)
分割文本文件中的行文本
读取文本内容,并且将每行分割成单词。
with open("my_file.txt", "r") as my_file:
for line in my_file:
str = line.split()
print(str)