##!/bin/python # 解释器路径,linux 下需要写 #!/bin/python import os import re import sys file_path = os.path.abspath(__file__) # 获取当前文件路径 dir_path = os.path.dirname(file_path) # 获取 文件的 路径 print("The current file is at: " + file_path) print("The directory of the current file is at: " + dir_path) #批量修改文件名 #批量修改图片文件名 zidir="1" # 定义子路径 DirPath = os.path.join(dir_path, zidir) # 拼接路径: 变量路径(当前路径)+子路径 print("#------------ 拼接路径: "+str(DirPath)) def renameall(): # 定义函数 fileList = os.listdir(DirPath) # listdir 函数 获取目录和文件 print("修改前:"+str(fileList)) # 输出文件夹中包含的文件 currentpath = os.getcwd() # 获取当前工作目录 os.chdir(DirPath) # chdir 改变当前工作路径 num=1 # 名称变量 for fileName in fileList: # 定义 fileName 是 fileList 数组的所有元素,并for 循环全部遍历 pat=".+\.(jpg|png|gif|py|txt)" # 匹配文件名(后缀文件)正则表达式 pattern = re.findall(pat,fileName) # 再列表 fileName 中查找 后缀名 pat 匹配的文件,最终成为一个列表 os.rename(fileName,(str("eiscSetOK_")+str(num)+'.'+pattern[0])) # 文件重新命名函数 num = num+1 # 改变编号,继续下一项 print("------------------------- file --------------------------") os.chdir(currentpath) # 改回程序运行前的工作目录 sys.stdin.flush() # 刷新 print("修改后:"+str(os.listdir(DirPath))) # 输出修改后文件夹中包含的文件 renameall() # 执行定义的函数 #---------- 修改文件内容 -----------# import os file="eiscSetOK_1.txt" fileset=os.path.join(DirPath,file) # 定义需要修改的文件 def replace_line_with_keyword(file_name, keyword, new_line): with open(file_name, 'r') as file: lines = file.readlines() with open(file_name, 'w') as file: for line in lines: if keyword in line: file.write(new_line + '\n') else: file.write(line) def main(): file_name = fileset keyword = input("请输入要匹配的关键字:") new_line = input("请输入新的行内容:") replace_line_with_keyword(file_name, keyword, new_line) print("文件内容替换成功!") if __name__ == "__main__": main() #----- 在函数中调用其他函数 -----# def calculate_sum(a, b): return a + b def calculate_product(a, b): return a * b def calculate_sum_and_product(a, b): # 定义运行函数,来调用上面两个函数 sum_result = calculate_sum(a, b) # 定义变量 的结果为 执行函数传入数值运行的结果 product_result = calculate_product(a, b) # 返回计算得到的和与积 return sum_result, product_result # 反馈两个变量函数 # 调用calculate_sum_and_product函数,并获取它的返回值 sum_result, product_result = calculate_sum_and_product(5, 3) # 定义两个变量 等于函数传入的数值结算结果 print("The sum is:", sum_result) print("The product is:", product_result)