04文件操作(批量修改文件名)
1.批量修改文件名
In [2]:
import os os.getcwd()Out[2]:
'C:\\Users\\Administrator\\PycharmProjects\\python进阶'In [3]:
file_list=os.listdir("test/") #读取目录下的所有文件名,形成字符串列表In [4]:
file_list
Out[4]:
['1', '2', '3']In [5]:
# 利用相对路径进行修改 for f in file_list: dest_file = "re-" + f os.rename("test/" + f, "test/" + dest_file)In [6]:
file_list=os.listdir("test/") file_listOut[6]:
['re-1', 're-2', 're-3']In [7]:
# 利用绝对路径进行修改 for f in file_list: dest_file = "re-" + f 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)In [8]:
file_list=os.listdir("test/") file_listOut[8]:
['re-re-1', 're-re-2', 're-re-3']
2.从某个目录下,读取包含某个字符串的某种类型的文件有哪些?¶
例如:从/home/python目录下读取包含hello的.py文件有哪些?
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。 In [11]:def read_and_find_hello(dir): pass def find_hello(dir): if os.path.isdir(dir): # 如果传入的是一个目录 pass else: if dir.endswith('py'): # 传入的文件是否以py结尾 if read_and_find_hello(dir): # 读取该py文件,并且看看文件中是否包含hello passIn [12]:
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 flagIn [13]:
filename = 'test\\1.py' read_and_find_hello(filename)Out[13]:
TrueIn [14]:
filename = 'test\\2.py' read_and_find_hello(filename)Out[14]:
FalseIn [26]:
# 以上单个方法测试通过 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 file_abspath.endswith(".py"): # 如果传入的文件就是文件,判断文件名是否以.py结尾 if read_and_find_hello(file_abspath): # 读取该py结尾的文件,并且看看文件内容中是否包含有hello file_list.append(file_abspath)In [27]:
path1 =os.path.abspath("python进阶") path1Out[27]:
'C:\\Users\\Administrator\\PycharmProjects\\python进阶\\python进阶'In [28]:
path2 = os.path.abspath("test") path2Out[28]:
'C:\\Users\\Administrator\\PycharmProjects\\python进阶\\test'In [29]:
find_hello(path1, path2)In [30]:
file_list
Out[30]:
['C:\\Users\\Administrator\\PycharmProjects\\python进阶\\test\\1.py']

更多精彩