Please enable java script to visit.
NOTEBOOK
HOMEPHP / MySQLJS / HTMLWXappPythonC++Blender其他
Python 从文件读取数据,将数据写入文件 - NOTEBOOK
Python 从文件读取数据,将数据写入文件
Python
Posted on 2023-05-24
摘要 : Python中的文件读写操作主要涉及以下几个函数:

open() : 打开一个文件,返回一个文件对象;
read()/readline() : 从文件中读取数据;
write()/writelines() : 向文件中写入数据
close() : 关闭文件。

此外,在操作文本内容时,还需要考虑操作系统的换行符问题。在 Windows 中,换行的方法是 \r\n,而在 Unix 和 Mac OS X 中则是 \n。因此,在跨平台的开发过程中,需要注意统一应用换行符。
newline = os.linesep : # 获取操作系统所支持的换行符,Windows 为"\r\n",其他为"\n"
❱ 文件打开

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=true, opener=None)

mode参数:
r 读取,默认模式。
w 写入,如果文件已存在则覆盖,不存在则创建
a 追加,文件指针在文件尾部,如果文件不存在则创建
x 创建,如果文件已存在则抛出错误,不存在则创建。
b 二进制模式。
t 文本模式,默认模式。
+ 读写模式,在原有模式基础上增加读写功能。

encoding:使用指定的字符编码打开文件。例如,'utf-8'、'gbk' 等。
buffering:控制文件的缓冲方式。当 buffering = 0 时,文件不会被缓冲,当 buffering = 1 时,文件会被缓冲。当 buffering = 大于 1 的整数时,代表缓冲区的大小。buffering=-1 是使用 Python 默认缓存策略的最好选择。不仅可以最大限度地利用缓存的优势提高文件读写效率,同时也可以避免滥用内存导致系统出现不必要的负担。


❱ 文件读取

Python文件读取有多个函数,其中最常用的是read()函数和readline()函数。
read()函数用于从文件中读取指定的字节数,并返回一个字符串对象,如果没有指定字节数,则读取整个文件内容。
读取行为会移动指针。
# 打开文件
file = open("file.txt", "r")

# 读取所有内容
content = file.read()

# 关闭文件
file.close()

# 输出内容
print(content)


readline()函数用于读取文件中的一行内容,并返回一个字符串对象。
# 打开文件
file = open("file.txt", "r")

# 读取一行内容
line = file.readline()

# 关闭文件
file.close()

# 输出内容
print(line)


在循环中逐行读取文件内容:
# 打开文件
file = open("file.txt", "r")

# 循环读取每行内容
while true:
line = file.readline()
if not line:
break
print(line)

# 关闭文件
file.close()



❱ 文件写入

# 打开文件
file = open("file.txt", "w")

# 写入字符串文本
file.write("hello world\n")

# 关闭文件
file.close()

在每行的末尾加上一个换行符:
# 打开文件
file = open("file.txt", "w")

# 写入多行字符串文本
file.write("hello world\n")
file.write("This is a test\n")

# 关闭文件
file.close()


更好的写法是使用文件对象的writelines()方法:
# 打开文件
file = open("file.txt", "w")

# 写入多行字符串文本
lines = ["hello world\n", "This is a test\n"]
file.writelines(lines)

# 关闭文件
file.close()


在循环中写入多行内容:
# 打开文件
file = open("file.txt", "w")

# 打开文件
for i in range(5):
file.write("hello world\n")

# 关闭文件
file.close()



❱ 文件关闭

文件操作完成后,需要关闭文件以释放文件对象,避免资源浪费和文件损坏。
# 关闭文件
file.close()



❱ 综合使用

# 文件读写操作示例

# 打开文件,如果不存在则创建
with open("test.txt", "w")as f:
f.write("hello world\n")
f.write("time flies\n")

# 读取文件内容
with open("test.txt", "r")as f:
print(f.read())

# 追加内容到文件
with open("test.txt", "a")as f:
f.write("python is fun\n")

# 读取文件内容
with open("test.txt", "r")as f:
print(f.read())

# 读取文件中的一行
with open("test.txt", "r")as f:
print(f.readline())

# 循环读取文件中的多行
with open("test.txt", "r")as f:
for line in f:
print(line)




❱ 读取文件,修改数据,写入前比较文件有没有被其他人修改过

import os

#文件位置
file_path = './file.txt'

# 读取文件时间和大小
presize = os.path.getsize(file_path)
premt = os.path.getmtime(file_path)
prect =os.path.getctime(file_path)

# 读取文件内容
with open(file_path,'r',encoding='utf-8')as file:
content = file.read()

#新内容
content += '\n新的数据'
# 。。。。。其他处理过程(若有)

# 写入前读取文件时间和大小
nowsize = os.path.getsize(file_path)
nowmt = os.path.getmtime(file_path)
nowct =os.path.getctime(file_path)
#比较
if presize==nowsize and premt==nowmt and prect==nowct:
with open(file_path,'w',encoding='utf-8')as file:
file.write(content)
print('文件保存成功')
else:
print('文件已其他人修改')