目录
pyhton在众多领域都体现了它的强大,在运维方面亦是如此.python也使得运维趋于自动化运维发展,也使其成为了未来的一种必然发展趋势。为了能更好地了解运维底层的东西,以及方便日后的工作,编者写了Linux的复制操作,Vim文本编辑器,Unix to Windows(文件格式转换),以及利用递归函数编写了能够遍历系统文件下的所有子文件夹以及文件。
另提供源码文件:https://github.com/Seichung/Python/tree/master/Python_Practical
复制操作:
# Author Scon
# -*- coding utf-8 -*-
# help()
def copy(src_file, dst_file):
with open(src_file, 'rb') as src_boj:
src_data = src_boj.read()
with open(dst_file, 'wb') as dst_obj:
if not src_data: # 如果数据为空的话就结束程序
exit()
dst_obj.write(src_data)
if __name__ == '__main__':
while True:
try:
file = input("Please enter the file that you want to copy: ").strip()
file_name = input("\nPlease enter the location you want to copy to:").strip()
copy(file, file_name)
print("\nSuccessful!")
except FileNotFoundError:
print("\n\033[31;1mPlease enter the file path.Try again.\033[0m")
except KeyboardInterrupt:
print("\nGoodBye!")
break
else:
break
Vim的文本编辑器:
# Author Scon
# -*- coding utf-8 -*-
# help()
import os
def get_fname():
while True:
try:
tip = 'Notice'
print("\n\033[31;1m %30s \033[0m" % tip)
print("If no absolute path is entered, the generated file will in the program directory\n")
except KeyboardInterrupt:
break
fname = input('Please enter the filename: ')
if not os.path.exists(fname):
break
print('\n\033[31;1m"%s" already exists. Try again\n\033[0m' % fname)
return fname
def get_content():
content = []
print('\nPlease enter data,and enter \033[31;1m"end"\033[0m to stop ')
while True:
line = input('\033[31;1m->\033[0m\033[34;1m ~\033[0m ')
if line == 'end':
print("GoodBye!")
break
content.append(line)
return content
def writefile(fname, content):
try:
with open(fname, 'w') as fobj:
fobj.writelines(content)
except FileNotFoundError:
print("\n\033[31;1mInvalid Enter.Please enter the file path\033[0m")
if __name__ == '__main__':
fname = get_fname()
content = get_content()
content = ['%s\n' % line for line in content]
writefile(fname, content)
Unix To Windows(文件格式转换):
# Author Scon
# -*- coding utf-8 -*-
# help()
import sys
import os
class File_Coversion:
'Convert File'
def __init__(self, file):
self.file = file
def to_unix(self):
unixflie = os.path.splitext(self.file)[0] + '_unix.txt'
with open(self.file, 'r') as fwindowsobj:
with open(unixflie, 'w') as funixobj:
for line in fwindowsobj:
lines = line.rstrip() + '\n'
funixobj.write(lines)
def to_windows(self):
windowsfile = os.path.splitext(self.file)[0] + '_windows.txt'
with open(self.file, 'r') as funixobj:
with open(windowsfile, 'w') as fwindowsobj:
for line in funixobj:
lines = line.rstrip() + '\r\n'
fwindowsobj.write(lines)
if __name__ == '__main__':
while True:
tips = """
[1] Unix To Windows
[2] Windows To Unix
[3] Exit
Please enter your choice (1/2/3):
"""
try:
choice = input(tips).strip()[0]
except IndexError:
print("\033[31;1mInvaild Input!\033[0m")
except KeyboardInterrupt:
break
else:
# 转换为windows格式
if choice == '1':
windows_file = input("\t \033[34;1mPlease enter you want to convert file :\033[0m")
conversion = File_Coversion(windows_file)
conversion.to_windows()
print("\t\033[31;1mConvert Successful!\033[0m")
# 转换为Unix格式
elif choice == '2':
unix_file = input("\t \033[34;1mPlease enter you want to convert file :\033[0m")
conversion = File_Coversion(unix_file)
conversion.to_unix()
print("\t \033[31;1mConvert Successful!\033[0m")
elif choice == '3':
exit()
else:
print('\t', "\033[31;1mInvaild Input!\033[0m")
递归遍历系统文件夹:
# Author Scon
# -*- coding utf-8 -*-
# help()
import os
import os
all_file = [] # 创建字典存储查询到的值
def All_files(path):
fliepath = os.listdir(path) # 列出指定目录的文件
for file in fliepath:
filename = os.path.join(path, file) # 将一个或多个路径正确地连接起来。
# 需要注意的是,需要加入原本的路径以及新产生的文件夹,这样才会将路径和*路径的任何成员的串联
if os.path.isdir(filename): # 判断查找的出来的是文件还是文件夹,如果是文件夹则重新#调用函数执行判断,如果不是则将查询的结果以追加的方式存储到列表中
All_files(filename)
else:
all_file.append(filename)
return all_file
if __name__ == '__main__':
while True:
try:
file_path = input("Please enter the file that you want to query:").strip()
data = All_files(file_path)
print('\n', data, '\n')
except NotADirectoryError:
print("\n\033[44;30m'%s' is a file,Please enter the folder!\033[0m\n" % file_path)
except FileNotFoundError:
print("\n\033[31;1mInvalid Enter.Try again!\033[0m\n")
except (KeyboardInterrupt, EOFError):
break
# 第二种方法:
import os
def all_file(path):
filelist = []
filename = os.walk(path)
for file in filename:
filelist.append(file)
return filelist
if __name__ == '__main__':
while True:
try:
file_path = input("Please enter the file that you want to query:").strip()
data = all_file(file_path)
print('\n',data,'\n')
except NotADirectoryError:
print("\n\033[44;30m'%s' is a file,Please enter the folder!\033[0m\n" % file_path)
except FileNotFoundError:
print("\n\033[31;1mInvalid Enter.Try again!\033[0m\n")
except (KeyboardInterrupt,EOFError):
break
本文旨在提供参考,如有错误,欢迎大家指正。帮助编者不断的改进!