python09-文件操作(write())

21:06 2019/1/15/周二
文件操作之写操作
f=open("九门",'w',encoding="utf-8")//r 为只读,w只写(w这个操作是把文件夹里面的文件清空)文件如果不存在,那么就创建一个新的文件。
//write()写入文件。文件内容只能是字符串,只能写字符串。
f=open("九门",'w',encoding="utf-8")
f.write("11111111\t22222222\n3333333\n")
f.close()
print()
8:50 2019/1/16/周三
//也可以通过with 对应用程序进行调用,,f获取权限。这个时候是系统默认关闭文件。
with open("a.txt","w") as f:
     f.write("1111111222223333\n5555556666\n")

//追加
with open("a.txt","a",encoding="utf8") as f:
     f.write("追加的最后\n")
a是追加命令。
//其他操作命令。r+是可读可写。
with open("a.txt","r+",encoding="utf8") as f:
     f.write("追加的最后\n")
     f.write("追加的最后\n")
     print(f.readline())
//通过readlines()读取的是列表的形式
data=src_files.readlines()
//模拟文件替换操作:
src_files=open("a","r",encoding="utf-8")
data=src_files.readlines()#读取文件放入data中,这个时候的data保                            #存的是list 类型的数据。
src_files.close()           
src_files1=open("a.txt","w",encoding="utf-8")
print(data,type(data))
src_files1.write(data[0])
src_files1.close()
// 利用with同样可以对上面的文件进行操作:
with open("a","r",encoding="utf-8") as src_files, open("a.txt","w",encoding="utf-8") as src_files1:
    data = src_files.readlines()
    src_files1.write(data[1])
显示结果一样。

猜你喜欢

转载自blog.csdn.net/qq_37431752/article/details/86514947