先来看下面的带码:
# 创建文件
context = '''hello world'''
f = open('hello.txt', 'w') # 打开文件
f.write(context) # 把字符串写入文件
f.close() # 关闭文件
第3行调用open()创建文件hello.txt,第4行写入,第5行调用close(),释放对象f占用的资源。
在同级目录下会生成hello.txt文档。
接下来是文件读取:
# 使用readline()读文件
f = open("hello.txt")
while True:
line = f.readline()
if line:
print (line)
else:
break
f.close()
此程序读取文件里的每一行。
输出为:
hello world
多行读取则是使用readlines()
# 使用readlines()读文件
f = open('hello.txt')
lines = f.readlines()
for line in lines: # 一次读取多行内容
print (line)
f.close()
一次性读取read():
# 使用read()读文件
f = open("hello.txt")
context = f.read()
print (context)
f.close()
控制read()参数:
f = open("hello.txt")
context = f.read(5) # 读取文件前5个字节内容
print (context)
print (f.tell()) # 返回文件对象当前指针位置
context = f.read(5) # 继续读取5个字节内容
print (context)
print (f.tell()) # 输出文件当前指针位置
f.close()
接下来看看文件的写入:
# 使用writelines()写文件
f = open("mygirl.txt", "w+")
li = ["hello world\n", "hello China\n"]
f.writelines(li)
f.close()
追加新内容的话,使用a+模式:
# 追加新的内容到文件
f = file("mygirl.txt", "a+") # 写入方式为追加a+
new_context = "goodbye"
f.write(new_context)
f.close()
如果需要写入文件的字符串非常多,可以使用writelines()加快写文件的速度。
再简单看下文件的删除:
import os
file("hello.txt", "w")
if os.path.exists("hello.txt"):
os.remove("hello.txt")