【编程】Python 文件操作

Python 程序不需要特殊的模块,即可以操作文件。文件对象包括基本函数和操作文件所需要的必要的各种方法,并且操作方法非常简单。

读取文本文件的方法,包括 read(),readline() 和 readlines()

  • read([number]) : 返回指定长度数量的字符,如果省略参数,则读取全部内容
  • readline() : 返回下一行数据
  • readlines() : 读取全部文件行到数组列表

读取整个文件内容

with open("my_file.txt", "r") as my_file:
str = my_file.read()
print(str)

输出

This is first line
This is second line
This is third line
This is fourth line

只读取一行

with open("my_file.txt", "r") as my_file:
str = my_file.readline()
print(str)

输出

This is my first line

使用长度读取数据

with open("my_file.txt", "r") as my_file:
str = my_file.read(38) #按长度读取文件
print(str)

输出

This is my first line
This is second line

将全部行读取到数组里面

with open("my_file.txt", "r") as my_file:
str = my_file.readlines()
print(str)

输出

[‘This is first line\n’, ‘This is second line\n’, ‘This is third line\n’, ‘This is fourth line’]

按行读文件

如果想较快的读取文件的所有行,可以使用循环。

例子

with open("my_file.txt", "r") as my_file:
for line in my_file:
print(line)

输出

This is first line
This is second line
This is third line
This is fourth 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)

例子

This is first line
20

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)

输出

This is first line
This is second line

分割文本文件中的行文本

读取文本内容,并且将每行分割成单词。

例子

with open("my_file.txt", "r") as my_file:
for line in my_file:
str = line.split()
print(str)

输出

[‘This’, ‘is’, ‘first’, ‘line’]
[‘This’, ‘is’, ‘second’, ‘line’]
[‘This’, ‘is’, ‘third’, ‘line’]
[‘This’, ‘is’, ‘fourth’, ‘line’]



【编程】python 写文件
【编程】Python 打开文件
【编程】Python 合并字典
【编程】Python 列表推导
【编程】Python 列表排序
【编程】Python 集合
【编程】Python 字典
【编程】Python 元组

此条目发表在人工智能, 服务器, 程序开发分类目录,贴了, , 标签。将固定链接加入收藏夹。