Python3之Linux系统管理

1.  文件读写

    1.  读取文件内容的过程

        1.  使用python内置的open函数打开文件

f=open('pyvenv.cfg')    #打开文件
print (f.read())     #读取文件所有内容
a=f.close()    #关闭文件

        2.  使用read函数,读取文件内容;使用write函数,写入文件内容

        3.  使用close函数,关闭文件

    2.  文件的打开模式

        

        例子:

          打开一个非空的已存在的文件,并写入数据

f=open('pyvenv.cfg','w')
print (f.write('yangjianbo zui niu bi '))
a=f.close()

    3.  避免文件句柄泄漏        

with open('pyvenv.cfg','r',encoding='utf-8') as f:
    print (f.read())

    4.  常见的文件操作函数

        1.  读函数

            read:  读取文件中的所有内容,光标移动到文件末尾

with open('test.txt','r') as f:
    print (f.read())
输出的结果
    a杨建波
    b罗莺
    c易长坤
    d侯震
    e乐享
    f京东 

            readline:  一次读取一行,光标移动第二行首部

with open('test.txt','r') as f:
    print (f.readline())
输出的结果
    a杨建波 

            readlines:  将文件内容存到一个列表中,列表中的每一个元素对应于文件中的一行

with open('test.txt','r') as f:
    print (f.readlines())
输出的结果:
    ['a杨建波\n', 'b罗莺\n', 'c易长坤\n', 'd侯震\n', 'e乐享\n', 'f京东'] 

        2.  写函数          

            1.  write  写字符串到文件中,并返回写入的字符数 

                文本模式写入 

with open('test.txt','w',encoding='utf-8') as f:
    f.write('黎明\n郭富城\n郑伊健\n')  #针对文本模式的写,需要自己写换行符

                非文本模式写入

with open('test2.txt','wb') as f:
    f.write('111\n222\n郑伊健\n'.encode('utf-8')) 

            2.  writelines  写一个字符串列表到文件中      

                文本模式写入

with open('test2.txt','w') as f:
    f.writelines(['333\n','444\n'])

                非文本模式写入          

with open('test2.txt','wb') as f:
    f.writelines([bytes('333\n', encoding='utf-8'), '444\n'.encode('utf-8')])

            3.  使用print写入文件

with open('test2.txt','w') as f:
    print (1,2,'hhaa',sep=',',file=f)

    5.  例子

        1.  写一个cp工具,可以拷贝任何文件

import sys
if len(sys.argv) != 3:
    print('usage: cp source_file target_file')
    sys.exit()

source_file,target_file=sys.argv[1],sys.argv[2]
with open(source_file,'rb') as read_f,open(target_file,'wb') as write_f:
    for line in read_f:
        write_f.write(line)

            执行命令:  test.py E:\fastdfs-zyc-fastdfs_client1.24.zip e:\1.zip

        2.  将文件中所有单词的首字母变成大写

with open('test2.txt','r') as inf,open('test3.txt','w') as outf:
    for line in inf:
        outf.write(" ".join([word.capitalize() for word in line.split()]))
        outf.write("\n")

            使用print函数进行输出

with open('test2.txt','r') as inf,open('test3.txt','w') as outf:
    for line in inf:
       print(*[word.capitalize() for word in line.split()],file=outf)

2.  文件与文件路径管理

    1.  os模块使用       

os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
os.chdir("dirname")  改变当前脚本工作目录;相当于shell下cd
os.curdir  返回当前目录: ('.')
os.pardir  获取当前目录的父目录字符串名:('..')
os.makedirs('dirname1/dirname2')    可生成多层递归目录
os.removedirs('dirname1')    若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
os.mkdir('dirname')    生成单级目录;相当于shell中mkdir dirname
os.rmdir('dirname')    删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
os.listdir('dirname')    列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
os.remove()  删除一个文件
os.rename("oldname","newname")  重命名文件/目录
os.stat('path/filename')  获取文件/目录信息
os.sep    输出操作系统特定的路径分隔符,win下为"\\",Linux下为"/"
os.linesep    输出当前平台使用的行终止符,win下为"\t\n",Linux下为"\n"
os.pathsep    输出用于分割文件路径的字符串 win下为;,Linux下为:
os.name    输出字符串指示当前使用平台。win->'nt'; Linux->'posix'
os.system("bash command")  运行shell命令,直接显示
os.environ  获取系统环境变量
os.path.abspath(path)  返回path规范化的绝对路径
os.path.split(path)  将path分割成目录和文件名二元组返回
os.path.dirname(path)  返回path的目录。其实就是os.path.split(path)的第一个元素
os.path.basename(path)  返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
os.path.exists(path)  如果path存在,返回True;如果path不存在,返回False
os.path.isabs(path)  如果path是绝对路径,返回True
os.path.isfile(path)  如果path是一个存在的文件,返回True。否则返回False
os.path.isdir(path)  如果path是一个存在的目录,则返回True。否则返回False
os.path.join(path1[, path2[, ...]])  将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
os.path.getatime(path)  返回path所指向的文件或者目录的最后存取时间
os.path.getmtime(path)  返回path所指向的文件或者目录的最后修改时间
os.path.getsize(path) 返回path的大小

    2.  拆分路径

import os
a=os.path.split('f:/yangjianbo/test.py')   #返回一个二次组
b=os.path.dirname('f:/yangjianbo/test.py')    #返回二次组的第一个元素
c=os.path.basename('f:/yangjianbo/test.py') #返回二次组的第二个元素
d=os.path.splitext('f:/yangjianbo/test.py') #返回二次组,第二个为扩展名
print (a)    
print (b)
print (c)
print (d)
输出的结果:
('f:/yangjianbo', 'test.py')
f:/yangjianbo
test.py
('f:/yangjianbo/test', '.py')

    3.  构建路径

import os
a=os.path.expanduser('~test')   #获取用户的home目录
b=os.path.abspath('test.py')  #获取文件或目录的绝对路径
c=os.path.join(os.path.expanduser('~test'),'t','a.txt')  #拼接路径
print (a)
print (b)
print (c)
输出的结果:
C:\Users\test
F:\yangjianbo\test.py
C:\Users\test\t\a.txt

    4.  获取文件属性

import os
a=os.path.getatime('F:/yangjianbo')
b=os.path.getctime('F:/yangjianbo')
c=os.path.getmtime('F:/yangjianbo')
d=os.path.getsize('F:/yangjianbo')
print (a)
print (b)
print (c)
print (d)
输出的结果:
1649302215.3910356
1646981022.6668346
1649302215.3910356
4096

    5.  判断文件类型

  

      

      

    

      

  

      

  

  

                    

          

 

posted @ 2022-04-07 13:04  奋斗史  阅读(156)  评论(0)    收藏  举报