
#文件打开
f=open("text.txt","w")
#文件写入
f.write("Hello Python")
#文件关闭
f.close()
读
read()
f=open("text.txt","r")
ctx=f.read()
f.close()
print(ctx) #Hello Python
readlines()
readline()
读取一行和整行
f = open("text.txt", "wb")
f.write(b"asdnasdnfghn123")
f.close()
f = open("text.txt", "r")
ctx = f.readlines()
f.close()
f = open("text.txt", "r")
ctx2 = f.readline()
f.close()
print(ctx) # ['asdn', 'asdn', 'fghn', '123']
print(ctx2) # asd
seek()
用来移动文件指针
⽂件对象.seek(偏移量, 起始位置)
起始位置:
- 0:⽂件开头
- 1:当前位置
- 2:⽂件结尾
f=open("text.txt","r+")# 进行读写 文件指针放在开头
ctx=f.read()
print(ctx)
# aaaaa
# bbbbb
# ccccc
ctx=f.read()
print(ctx) #无打印
f.seek(2,0)#相对开始位置偏移2个单位
ctx=f.read()
print(ctx)
# aaa
# bbbbb
# ccccc
f.close()
文件备份
# 文件名重构
old_name="text.txt"
i=old_name.index(".")
prefix=old_name[0:i]
suffix=old_name[i:]
backup="_backup"
new_name=prefix+backup+suffix
print(new_name)
old_f=open(old_name,"rb")
new_f=open(new_name,"wb")
while True:
ctx=old_f.read(1024)
if len(ctx)==0:
break
new_f.write(ctx)
old_f.close()
new_f.close()
文件及其文件夹操作
导入os
import os文件重命名
os.rename(⽬标⽂件名, 新⽂件名)删除文件
os.remove(⽬标⽂件名)创建文件夹
os.mkdir(⽂件夹名字)删除⽂件夹
os.rmdir(⽂件夹名字)获取当前⽬录
os.getcwd()改变默认⽬录
os.chdir(⽬录)获取⽬录列表
os.listdir(⽬录)应用案例
文件名字统一增加某字段或删除某字段
import os
while True:
flag = input("Do you want to Add a fileString or Delete a fileString?(A/D):")
if flag != "A" and flag != "D":
print("input error!")
break
dir_name=input("please input directory name:")
os.chdir("E:\python-test\test\"+dir_name)
dir_list=os.listdir()
default_name="Python-"
for name in dir_list:
if flag=="A":
new_name=default_name+name
if flag=="D":
new_name=name[len(default_name):]
print(new_name)
os.rename(name,new_name)
qt=input("input Q to exit:")
if qt=="Q" or qt=="q":
break