#文件输入输出:读写 """ 1.打开文件:open(文件名,打开的读写模式) r:只读 w:写入,文件存在则覆盖,文件不存在则新建 a:追加文件存在则追加 (b)binary :二进制 rb:以二进制格式打开文件,只读模式 wb: ab: """ """ 2. 使用open()函数:可以打开已存在的文件 close() 关闭文件 例:新建a.txt 、b.txt文件 """
fa=open("a.txt","w") #打开文件后返回到变量fa
# fb=open("b.txt","w") #打开文件后返回到fb
my_cont="abcde\n"
fa.write(my_cont)
fa.close() #关闭a文件,打开文件后,不用时关闭。
#2.读写
fb=open("b.txt","r")
#read()默认读取所有数据
my_cont=fb.read() #读取数据后,保存在变量my_cont中
print(my_cont)
fb.close()
文件a.txt、b.txt:
b.txt中的内容:
运行结果:
#1.文件模式
# w 默认覆盖文件中的数据
# w 文件不存在,则新建文件
# f=open("a.txt","w")
def readmodel():
f=open("a.txt","r")
content=f.read()
print(content)
f.close()
readmodel()
def writemodel():
# w 默认覆盖文件中的数据
# w 文件不存在,则新建文件
# f=open("a.txt","w")
f = open("a.txt", "a") #a 模式,追加写入
content=f.write("\nwerwetyweyrtuwrut")
print(content)
f.close()
writemodel()
写文件:
.write() 写一行
.writelines() 写多行
# 写文件:write
def write_text():
#写一行
f=open("b.txt","w")
f.write("hello ~")
#写多行
lines=["aaa\n","bbb\n","ccc\n"]
f.writelines(lines)
f.close()
write_text()
读取数据:
.read() : 默认读取所有数据
.read(n) : 指定参数,则读取指定个数的数据
def read_text():
f=open("a.txt","r")
con=f.read(3) #指定参数,则读取指定个数的数据,默认读取所有数据
f.close()
print(con)
read_text()
读取一行数据:readline()
print()
print("读取一行数据:readline()")
def read_text01():
# 读取一行数据
f=open("a.txt","r")
con=f.readline() #该行已经读完,下一次读第二行:
con1=f.readline()
f.close()
print(con)
print(con1)
read_text01()
读取多行数据:readlines()
def read_text02():
# 读取多行数据
f = open("a.txt", "r")
con = f.readlines() # 读取多行,返回列表[], 元素都有\n换行符
# print(con)
for v in con:
# print(v)
if v[-1]=="\n":
print(v[:-1])
else:
print(v)
f.close()
read_text02()
""" 文件拷贝: 步骤: 1.获得要拷贝的文件名 2.读取要拷贝的文件内容 3.打开新的文件 4.将old文件的内容写到new文件里 """
#获取
old_f_name=input("输入要拷贝的文件名")
#读取
new_f_name=old_f_name+"a.txt.css"
#打开
old_open=open(old_f_name,"rb")
new_open=open(new_f_name,"wb")
#写入
old_cont=old_open.read()
new_open.write(old_cont)
#关闭文件
old_open.close()
new_open.close()
# # #文件操作
# # #文件操作
import os
#文件重命名:os.rename()
def f_rename():
os.rename("e.txt","d.txt")
f_rename()
#文件删除os.remove()
def f_del():
os.remove("d.txt") #默认当前目录下查找文件,找不到时报错
# os.remove("指定路径")
f_del()
#创建、删除目录(文件夹)
os.mkdir("003") #默认当前目录下
os.rmdir("002")
cwd=os.getcwd() #获取当前目录
print(cwd)
os.mkdir('F:\My_Python\\13_20191202')