文件的基本操作
打开文件
f1 = open(r"C:\Users\Adminisrator\Desktop\haha.txt","r")
1.open函数的参数mode十分重要,它标志着以何种方式打开文件。
读文件
f1 = open(r"C:\Users\Adminisrator\Desktop\haha.txt","r")
data = f1.read()#用read函数读取文件
print(data)
f1.close()
read参数可以传递参数表示读取多少个字符。
按行读文件
当读入一个大文件时就不适合读入一个变量中,这时可以按行读取
f1 = open(r"C:\Users\Adminisrator\Desktop\haha.txt","r")
f1.readline()
print(f1.readline())#逐行读取文件内容
f1.close()
readlines函数会把文件内容按行切割,返回一个list列表对象。
f1 = open(r"C:\Users\Adminisrator\Desktop\haha.txt","r")
for read in f1.readlines():
print(read)
f1.close()
注意readlines函数会保留结尾的换行符,所以用print函数输出时会输出空白行。
直接迭代文件对象本身
f1 = open(r"C:\Users\Adminisrator\Desktop\haha.txt","r")
for read in f1:
print(read)
f1.close()
写文件
f1 = open(r"C:\Users\Adminisrator\Desktop\haha.txt","w")
data = "进行写文件操作"
f1.write(data)
f1.close()
1.以“w”模式打开文件每次都会从头开始覆盖原有内容,如果我们想在后面追加可以使用“a”模式。
按行写文件
writelines接受一个参数,这个参数必须是一个列表,列表的每一个参数就是想写进文本里的内容,但是我们在列表里要自行添加换行符。
f1 = open(r"C:\Users\Adminisrator\Desktop\haha.txt","w")
lines = ["123\n","456\n","789\n"]
f1.writelines(lines)
f1.close()
文件关闭
1.使用close函数关闭文件
2.使用with语句:Python解释器会在with语句代码执行完毕之后帮助我们执行close语句。
with open(r"C:\Users\Adminisrator\Desktop\haha.txt","w") as f1:
lines = ["123\n","456\n","789\n"]
f1.writelines(lines)
StringIo和BytesIo
前面介绍了关于文件的读写操作,但有时候数据并不需要真正的写入到文件中,只需要在内存中做到文件的读取和写入即可
写入
from io import StringIO
f = StringIO()
f.write("hello")
f.write(" ")
f.write("world")
print(f.getvalue())
读取
from io import StringIO
f = StringIO('hello\nworld\nwelcome\n')#创建StringIo对象,并初始化
while True:
s = f.readline()
if s=="":
break
print(s.strip())
StringIO的操作对象只能是str,如果要操作二进制数据,就要使用BytesIO
from io import BytesIO
f = BytesIO()
f.write("您好".encode("utf-8"))#写入一些bytes
print(f.getvalue())
print(f.getvalue().decode("utf-8"))
结果:
b'\xe6\x82\xa8\xe5\xa5\xbd'
您好
注意:写入的不是str,而是经过UTF-8编码的bytes
from io import BytesIO
f = BytesIO(b'\xe6\x82\xa8\xe5\xa5\xbd')
print(f.read().decode("utf-8"))
结果:
您好
来源:CSDN
作者:小驰驰呕吼**
链接:https://blog.csdn.net/weixin_43328054/article/details/104130080