版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/j086924/article/details/82782277
一.文本数据
1.用带有 rt 模式的 open() 函数读取文本文件,eg:
# 整个的文件以字符串的形式读取
with open('somefile.txt', 'rt') as f:
data = f.read()
# 通过每行迭代读取文件
with open('somefile.txt', 'rt') as f:
for line in f:
# 处理读取行的显示
2.用带有 wt ,at模式的 open() 函数写入文本文件,(wt覆盖掉之前的文件内容,at在之前文件内容后面添加)eg:
# 写字符文件到文本文件,覆盖掉文本中之前的文件
with open('somefile.txt', 'wt') as f:
f.write("text1")
f.write("text2")
# 写字符文件到文本文件,保存之前的文本文件在后面添加
with open('somefile.txt', 'at') as f:
f.write("text1")
f.write("text2")
3.临时文件的读写,需要引入包tempfile,临时文件内容没有保存,eg:
from tempfile import TemporaryFile
with TemporaryFile('w+t') as f:
f.write('Hello World\n')
f.write('Testing\n')
f.seek(0)
data = f.read()
print(data)
4.实例demo,test文件之前保存的内容为:"hello,jon!"
from tempfile import TemporaryFile
def read():
with open('/home/jon/mydoc/test', 'rt') as f:
data = f.read()
print(data)
def read1():
f = open('/home/jon/mydoc/test', 'rt')
data = f.read()
print(data)
f.close()
def write():
with open('/home/jon/mydoc/test', 'wt', encoding='utf-8') as f:
f.write("hello,world!")
def write1():
with open('/home/jon/mydoc/test', 'at', encoding='utf-8') as f:
f.write("welcome python !")
with TemporaryFile('w+t') as f:
f.write('Hello World\n')
f.write('Testing\n')
f.seek(0)
data = f.read()
print(data)
if __name__ == "__main__":
read()
print("------using 'rt' read-------")
read1()
print("-----using 'at' write--------")
write1()
read()
print("------using 'wt' write-------")
write()
read()
TemporaryFile()
5.运行result
Hello World
Testing
hello,jon!
------using 'rt' read-------
hello,jon!
-----using 'at' write--------
hello,jon!
welcome python !
------using 'wt' write-------
hello,world!
Process finished with exit code 0
注意事项:读写文本文件一般来讲是比较简单的,但是也需要注意,实例中的 with 语句给被使用到的文件创建了一个上下文环境,但 with 控制块结束时,文件会自动关闭,如果不使用 with 语句,记得手动关闭文件.