python os 模块介绍
"""
重命名文件
os.rename(src,dst)
os.rename('123.txt','124.txt')
删除文件
os.remove(path)
os.remove('123.txt')
创建目录
os.mkdir()
创建多级目录
os.makedirs()
删除目录
os.rmdir()
删除多级目录
os.removedirs()
获取当前目录
os.getcwd()
修改所在目录
os.chdir()
判断文件是否存在
os.path.exists()
判断是否为文件
os.path.isfile()
判断是否为目录
os.path.isdir() 获取绝对路径
os.path.abspath()
判断是否为绝对路径
os.path.isabs()
获取路径的最后部分
os.path.basename()
获取父级路径
os.path.dirname() 获取文件夹内的子文件(重要)
os.listdir() """
import os
# os.rename("log.txt","log.properties")
# os.remove("log.properties")
# open("log.txt","w")
# os.mkdir("abc")
# os.rmdir("abc")
# os.makedirs("a/b/c/d")
# os.removedirs("a/b/c/d")
# os.chdir("../")
# print(os.getcwd())
# file_name = "abc.jpeg"
# if os.path.exists(file_name):
# if os.path.isdir(file_name):
# print("删除文件夹成功")
# os.rmdir(file_name)
# elif os.path.isfile(file_name):
# print("删除文件成功")
# os.remove(file_name)
# else:
# print("文件不存在") path = os.getcwd() for f in os.listdir(path):
if f.endswith(".py"):
print(f)
os.walk方法,主要用来遍历一个目录内各个子目录和子文件。
os.walk(top, topdown=True, onerror=None, followlinks=False)
可以得到一个三元tupple(dirpath, dirnames, filenames),
第一个为起始路径,第二个为起始路径下的文件夹,第三个是起始路径下的文件。
dirpath
是一个string,代表目录的路径,
dirnames
是一个list,包含了dirpath下所有子目录的名字。
filenames
是一个list,包含了非目录文件的名字。
for (path, dirs, files) in os.walk(r"E:\怪奇物语\work"):
print(path) # 路径名
print(dirs) # 包含的文件夹名
print(files) # 包含的文件
print("--"*10)

以文件的默认编码打开此文件
with open("your_file", 'rb') as fp:
file_data = fp.read()
result = chardet.detect(file_data)
file_content = file_data.decode(encoding=result['encoding'])
几个案例
# 1.封装自定一个函数,可以将Iterable对象中的所有数据写到目标文件file中,
# 如果Iterable中存储的不是字符串,转换为字符串处理 def write_lines(file, Iterable):
with open(file, mode="a", encoding="utf-8") as f:
for i in Iterable:
if isinstance(i, str):
f.write(i + '\n')
else:
f.write(str(i) + "\n") # write_lines("1.txt",[1,2,3,4,5,6,"abcde"])
# 2.自定义一个函数,可以实现文件的复制(先读取目标文件,然后写入新文件)
# 比如:def copyfile(file) 将file复制一份,被复制出来的文件名为file_副本.后缀
def copyfile(file):
filetup = file.rpartition(".")
new_name = str(filetup[0]) + "_副本" + str(filetup[1] + filetup[2])
if os.path.exists(file):
with open(file, mode="r", encoding="utf-8") as f:
with open(new_name, mode="w", encoding="utf-8") as f1:
content = f.read(1024)
while content:
f1.write(content)
content = f.read(1024)
else:
print("file not exists") # copyfile("digui.py")
# 3.打印某个文件夹内所有的的文件名
def print_all_file(file_path):
file_list = os.listdir(file_path)
for f in file_list:
f = file_path + "\\" + f
if os.path.isfile(f):
print(f)
elif os.path.isdir(f):
print_all_file(f) # print_all_file(r"E:\python workspace\day13")
# 4.尝试将一个文件夹内所有的.py文件名前都添加上你的名字做前缀(注意文件先备份)
# 例如:test01.py -> xxx_test01.py
def add_prefix(file_path, prefix):
file_list = os.listdir(file_path)
for f in file_list:
f = file_path + "\\" + f
if os.path.isfile(f):
basename = os.path.basename(f)
dirname = os.path.dirname(f)
# print(dirname+"\\"+prefix+basename)
os.rename(f, dirname + "\\" + prefix + basename)
elif os.path.isdir(f):
add_prefix(f, prefix) # add_prefix(r"E:\python workspace\day13","songdan_")
# 5.封装一个函数,可以实现类似操作系统的模糊查询功能(输入一个关键字,可以展示目标文件夹中包含关键字的所有文件)
import chardet def find_file_contains_key(f,key):
if key in f:
print(f"包含{key}的文件名为:{f}:")
with open(f, mode="rb") as fp:
file_data = fp.read()
result = chardet.detect(file_data)
file_content = file_data.decode(encoding=result['encoding'])
now_fname = ""
for line in file_content:
line = line.strip()
if key in line:
if now_fname == "":
now_fname = f.name
print(f"包含内容为{key}的文件名为:{f.name}:") print(f"\t\t内容为:{line}") def show_file_by_word(file_path, key):
file_list = os.listdir(file_path)
for f in file_list:
f = file_path + "\\" + f
# 文件,查询里面是否包含关键字
if os.path.isfile(f) and f.endswith(".py"):
find_file_contains_key(f,key)
# 文件夹,找出里面的文件
elif os.path.isdir(f):
show_file_by_word(f, key) show_file_by_word(r"E:\python workspace\day13", "songdan")
# 6.统计某个文件夹内所有.py文件中的代码行数
count = 0
def count_file_words(file_path):
file_list = os.listdir(file_path)
global count
for f in file_list:
f = file_path + "\\" + f
if os.path.isfile(f) and f.endswith(".py"):
with open(f, mode="r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if "#" not in line and len(line) > 0:
count += 1 # 文件夹,找出里面的文件
elif os.path.isdir(f):
count_file_words(f) return count # count_file_words(r"E:\python workspace\day13\test")
print(count)
更多案例参见:https://github.com/geekcomputers/Python/tree/master/
python os 模块介绍的更多相关文章
- Python—os模块介绍
OS模块 我们平时工作中很常用到的一个模块,通过os模块调用系统命令,获得路径,获取操作系统的类型等都是使用该模块.os 模块提供了很多允许你的程序与操作系统直接交互的功能 得到当前工作目录,即当前P ...
- Python os模块介绍
os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径 os.chdir("dirname") 改变当前脚本工作目录:相当于shell下cd os.curd ...
- Python OS模块常用功能 中文图文详解
一.Python OS模块介绍 OS模块简单的来说它是一个Python的系统编程的操作模块,可以处理文件和目录这些我们日常手动需要做的操作. 可以查看OS模块的帮助文档: >>> i ...
- python file对象测试数据的读写操作及OS模块介绍(四)
import from....import 引入模块 引入类 ①import 如果文件在lib下而且是python模块 :import 模块名. ②from....import from 包名.包 ...
- Python day18模块介绍2(使用BASE_DIR修改临时path,os模块)
1.BASE_DIR修改path(别人导入py项目时不会因为绝对路径无法解释) #sys修改环境变量 #使用BASE_DIR将绝对路径改为相对路径 import sys,os BASE_DIR=os. ...
- Python::OS 模块 -- 进程参数
os模块的简介请参看 Python::OS 模块 -- 简介 os模块的文件和目录操作 Python::OS 模块 -- 文件和目录操作 os模块的进程管理 Python::OS 模块 -- 进程管理 ...
- Python::OS 模块 -- 进程管理
os模块的简介参看 Python::OS 模块 -- 简介 os模块的文件相关操作参看 Python::OS 模块 -- 文件和目录操作 os模块的进程参数 Python::OS 模块 -- 进程参数 ...
- Python::OS 模块 -- 文件和目录操作
os模块的简介参看 Python::OS 模块 -- 简介 os模块的进程管理 Python::OS 模块 -- 进程管理 os模块的进程参数 Python::OS 模块 -- 进程参数 os模块中包 ...
- python OS 模块 文件目录操作
Python OS 模块 文件目录操作 os模块中包含了一系列文件操作的函数,这里介绍的是一些在Linux平台上应用的文件操作函数.由于Linux是C写的,低层的libc库和系统调用的接口都是C AP ...
随机推荐
- #include <filename.h> 和 #include“filename.h” 有什么区别
对于#include <filename.h> ,编译器从标准库路径开始搜索filename.h,对于#include “filename.h” ,编译器从用户的工作路径开始搜索filen ...
- Java中"str1.equals(str2)"和"str1==str2"的区别
大家好,这是我的第一篇博客,作为即将入职的学生,我现在的心情是既好奇又兴奋,对未知的职场生活充满了无限的憧憬,也想赶紧对大学生活say goodbye,因为自己的能力现在还比较有限,我想通过博客这个平 ...
- 如何使用JMeter 进行压力测试
文件转载至:https://jingyan.baidu.com/album/a681b0de5b85db3b184346b9.html?picindex=2 1.打开JMeter, 更改语言为中文,官 ...
- 《数据结构与算法分析——C语言描述》ADT实现(NO.01) : 栈(Stack)
这次的数据结构是一种特殊的线性表:栈(Stack) 栈的特点是后入先出(LIFO),可见的只有栈顶的一个元素. 栈在程序中的地位非常重要,其中最重要的应用就是函数的调用.每次函数调用时都会创建该函数的 ...
- 详解Spring MVC 4常用的那些注解
Spring从2.5版本开始在编程中引入注解,用户可以使用@RequestMapping, @RequestParam, @ModelAttribute等等这样类似的注解.到目前为止,Spring的版 ...
- Luogu P2764 最小路径覆盖问题(二分图匹配)
P2764 最小路径覆盖问题 题面 题目描述 «问题描述: 给定有向图 \(G=(V,E)\) .设 \(P\) 是 \(G\) 的一个简单路(顶点不相交)的集合.如果 \(V\) 中每个顶点恰好在 ...
- Leetcode82. Remove Duplicates from Sorted List II删除排序链表中的重复元素2
给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字. 示例 1: 输入: 1->2->3->3->4->4->5 输出: 1-&g ...
- 过滤html标签的一个函数
str_replace(array(' ', '&', '"', ''', '“', '”', '—', '<', '>', '·', '…', '&'), ar ...
- 【python之路24】装饰器
1.装饰器的应用场景 通常IT公司的程序开发是分工的,例如某公司某个部门负责底层函数的开发,另一个部门利用其函数实现高级功能,那么如果负责底层开发的函数需要改动,一般来说不会直接在函数上进行修改,通常 ...
- LintCode 两两交换链表中的节点
给一个链表,两两交换其中的节点,然后返回交换后的链表. 样例 给出 1->2->3->4, 你应该返回的链表是 2->1->4->3. 分析:第一次调试的时候用了P ...