python3基础(九)-系统文件相关操作

1、import os

os.rename("test1.txt" , "test2.txt")    #修改文件名称
os.path.abspath("test2.txt")    #获取文件绝对路径
os.path.getsize("test2.txt")    #获取文件大小

2、批量修改文件名

#提前在程序文件执行目录下新建一test目录,并在test目录下存入几个文件。
import os
file_list=os.listdir("test/")    #读取目录下的所有文件名,形成字符串列表
for f in file_list:
    dest_file="re-"+f
    os.rename("test/"+f, test/"+dest_file)    #记住这里的文件是包含文件的路径的,这个路径就是程序执行的路径,当然也可以使用绝对路径
    parent_dir=os.path.abspath("test")    #获取父目录的绝对路径
    source_file=os.path.join(parent_dir, f)    #字符串拼接,拼接源文件绝对路径
    dest_file=os.path.join(parent_dir, dest_file)    #拼接修改后的文件绝对路径
    os.rename(source_file, dest_file)

3、从某个目录下,读取包含某个字符串的某种类型的文件有哪些?

例如:从/home/python目录下读取包含hello的.py文件有哪些?
import os
file_list=[]
#递归函数,该函数中所有的文件路径全部采用绝对路径,parent_dir:文件所在父目录的绝对路径,file_name表示当前你要处理的文件或目录
def find_hello(parent_dir, file_name):
    file_abspath=os.path.join(parent_dir, file_name)    #当前正在处理的文件或者目录的绝对路径
    if os.path.isdir(file_abspath):    #如果传入的文件是一个目录
        for f in os.listdir(file_abspath):    #进入目录,列出该目录下的所有文件列表
            find_hello(file_abspath, f)    #调用函数本身,传入父目录和本身名称进行判断和处理
    else:
        if dir.endswith(".py"):    #如果传入的文件就是文件,判断文件名是否以.py结尾
            if read_and_find_hello(file_abspath):     #读取该py结尾的文件,并且看看文件内容中是否包含有hello
                file_list.append(file_abspath)

def read_and_find_hello(py_file):
    flag=False
    f=open(py_file)    #打开文件准备读取路径
    while True:
        line=f.readline()     #读取文件内容,一行一行的读取
        if line=='':    #文件读到最后一行,终止循环
            break
        elif "hello" in line:
            flag=True
            break
    f.close()
    return flag

find_hello("/home", "python")
print(file_list)

4、字符串创建的方法

str="%s好好好%s"%(a,b)
str="111111"
str="aaa".append("bbb")
str="aaa"+"bbb"

作者:沧水巫云
博客:http://blog.csdn.NET/amir_zt/
以上原创,转载请注明出处,谢谢。
https://blog.csdn.net/amir_zt/article/details/83655103

猜你喜欢

转载自blog.csdn.net/u011635351/article/details/83655103