文件
1.创建文件
2.打开 open()文件
3.处理(读read()写write())文件
4.关闭 close()文件
#==============================================================================
# #读文件
# f = open("text.text",mode="r",encoding="utf-8")
# f_content = f.read()
# print(f_content)
# f.close()
#==============================================================================
#==============================================================================
# #写(覆盖)文件
# f = open("text.text",mode="w",encoding="utf-8")
# w_content = f.write("write重写了这个文件")
# print(w_content)
# f.close()
#==============================================================================
#==============================================================================
# #追加文件内容
# f = open("text.text",mode="a",encoding="utf-8")
# a_content = f.write("write追加了这个内容")
# print(a_content)
# f.close()
#==============================================================================
#常规操作函数化
def Read_Write_File(filePath,mode_Type,Ope_Choice,size = None):
'''
filePath: 为文件路径+文件名 例如:D:\Python\Foundation Stage\stage1\text.text
mode_Type: r|w|a
size: 读取内容的大小,默认为None,整型
Ope_Choice: 读写操作read|write
'''
if Ope_Choice == "read":
f = open("filePath","mode_Type","Ope_Choice",encoding="utf-8")
print(f.read(size))
f.close()
elif Ope_Choice == "write":
f = open("filePath","mode_Type","Ope_Choice",encoding="utf-8")
print(f.write("write写了这个文件"))
f.close()
else:
print("请填写操作类型(read|write)")
平时应用:文件读写操作后自动关闭释放资源(with as)
'''
file = open("/tmp/foo.txt")
data = file.read()
file.close()
#传统的try...finally语法
file = open("/tmp/foo.txt")
try:
data = file.read()
finally:
file.close()
#with...as
with open("/tmp/foo.txt") as file:
data = file.read()
'''
dict = [
{"user1":123456},
{"user2":123456}
]
with open("d.txt","w") as f2:
for i in dict:
for key,value in i.items():
f2.write("{0}:{1}\n".format(key,value))
with open("d.txt","r") as f:
#一次性读取readlines()
content = f.readlines()
i = 1
for temp in content:
print("%d:%s"%(i,temp))
i+= 1
'''
1:user1:123456
2:user2:123456
'''
import csv
with open("123.csv","r") as f3:
list = []
content = csv.reader(f3)
for i in content:
i.append(list)
print(list)