栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 软件开发 > 后端开发 > Python

Python-语法学习-{文件操作,文件夹操作,应用案例}

Python 更新时间:发布时间: 百科书网 趣学号
文件操作 写入


#文件打开
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
转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/273292.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号