Python和运维

来自linux中国网wiki
跳到导航 跳到搜索

python常用的运维脚本

py3 批量修改文件后缀名 或者去掉后缀名

#!/usr/bin/python3
# -*- coding:utf-8 -*-

# python批量更换后缀名 注意  需要把脚本放在与修改的文件同一目录下,因为filenames只是获取了程序目录的文件名。
import os

# 列出当前目录下所有的文件
files = os.listdir('.')
for filename in files:
	portion = os.path.splitext(filename)
	# 如果后缀是.dat
	if portion[1] == ".txt":
		#  这里是把 .txt去掉     重新组合文件名和后缀名
		newname = portion[0]

		#txt 文件改为sh 要用这个记得打开下行注释
		#newname = portion[0] + ".sh"

		#os.rename(filename,newname)
		os.replace(filename,newname)

# As of Python version 3.3 and later, it is generally preferred to use os.replace instead of os.rename so FileExistsError is not raised if the destination file already exists.



#!/usr/bin/python3
# -*- coding:utf-8 -*-
# python批量更换后缀名 进入目录的版本 利用os.chdir
import os
import  sys
os.chdir(r'~/tmp')

# 列出当前目录下所有的文件
files = os.listdir('./')
print('files',files)

for filename in files:
	portion = os.path.splitext(filename)
	# 如果后缀是.txt
	if portion[1] == ".txt":
		#  这里是把 .txt去掉     重新组合文件名和后缀名
		newname = portion[0]

		#txt 文件改为sh 要用这个记得打开下行注释
		#newname = portion[0] + ".sh"

		os.rename(filename,newname)
		#os.rename(filename,newname)




python批量更换后缀名 会返回脚本所在目录的版本

#!/usr/bin/python3
# -*- coding:utf-8 -*-
# python批量更换后缀名 会返回脚本所在目录的版本
import os
import  sys

# Set the path
path ='~'
# save current working directory
saved_cwd=os.getcwd()
# change your cwd to the directory which contains files
os.chdir(path)

# 列出当前目录下所有的文件
files = os.listdir('./')
print('files',files)

for filename in files:
	portion = os.path.splitext(filename)
	# 如果后缀是.txt
	if portion[1] == ".txt":
		#  这里是把 .txt去掉     重新组合文件名和后缀名
		newname = portion[0]

		#txt 文件改为sh 要用这个记得打开下行注释
		#newname = portion[0] + ".sh"

		os.rename(filename,newname)
		#os.rename(filename,newname)

os.chdir(saved_cwd)

# https://stackoverflow.com/questions/2491222/how-to-rename-a-file-using-python#2491232

python文件操作3--批量修改文件后缀名


github.com 一些常用的Python脚本

Python运维常用的脚本,提高工作效率就靠它了

python常用的运维脚本有哪些

zhihu 你用 Python 写过哪些有趣的脚本?

python爬取廖雪峰教程存为PDF

os.path.splitext

os.path.splitext(“文件路径”) 分离文件名与扩展名;默认返回(fname,fextension)元组,可做分片操作

https://www.cnblogs.com/rychh/articles/9745932.html

https://blog.csdn.net/u011509971/article/details/70244688

R

python 遍历文件夹下所有文件名 并去掉后缀存入txt