Python檔案管理、亂碼及對passwd檔案排序

來源:互聯網
上載者:User

標籤:__name__   etc   pen   think   local   /dev/null   cer   lib   inpu   

1.讀寫檔案

讀檔案:

    f = open("1.txt")    text = f.readlines()    print(text)


寫檔案:


    f = open("2.txt",'w')encoding='utf-8'    f.write("Hello World!")    f.close()

代碼:

class File():    ENCODING = "utf-8"    def wirteFile(self):        filename = input("Please input the file name: ")        f = codecs.open(filename,'w',encoding=File.ENCODING)        while 1:            context = input("Please input the file context: ")            if context == "EOF":                break            f.write(context)            f.write("\n")    def readFile(self):        print("####################STAT######################")        readfile = input("Please input your read file name: ")        fileread = codecs.open(readfile,encoding=File.ENCODING)        readContext = fileread.read()        print(readContext)        print("################### END ######################")        fileread.close()if __name__ == '__main__':    import codecs    File = File()    File.wirteFile()    File.readFile()

執行過程:

Please input the file name: fxq.logPlease input the file context: Hello world!Please input the file context: My name is FengxiaoqingPlease input the file context: I'm 30Please input the file context: I'm a bright boy.lPlease input the file context: Think you very much!Please input the file context: EOF####################STAT######################Please input your read file name: fxq.logHello world!My name is FengxiaoqingI'm 30I'm a bright boy.lThink you very much!################### END ######################進程已結束,結束代碼0

2. 檔案方法

檔案常用方法:

    readline()

    readlines()

    next()

    read()

    write()         寫入的是字串

    writelines()    參數是序列,比如列表,它會迭代幫你 寫入檔案

檔案屬性:

    f.name

    f.closed

    f.encoding

    f.mode

with用法:


    with codec.open("1.log",encoding= "utf-8") as f:        print(f.read())

3.python2的亂碼問題


python2中:

import sys

reload(sys)

print(sys.getdefaultencoding())

4.python對passwd檔案進行排序

密碼檔案:

[[email protected] ~]# cat passwd.txtroot:x:0:0:root:/root:/bin/bashbin:x:1:1:bin:/bin:/sbin/nologindaemon:x:2:2:daemon:/sbin:/sbin/nologinadm:x:3:4:adm:/var/adm:/sbin/nologinlp:x:4:7:lp:/var/spool/lpd:/sbin/nologinsync:x:5:0:sync:/sbin:/bin/syncshutdown:x:6:0:shutdown:/sbin:/sbin/shutdownhalt:x:7:0:halt:/sbin:/sbin/haltmail:x:8:12:mail:/var/spool/mail:/sbin/nologinoperator:x:11:0:operator:/root:/sbin/nologingames:x:12:100:games:/usr/games:/sbin/nologinftp:x:14:50:FTP User:/var/ftp:/sbin/nologinnobody:x:99:99:Nobody:/:/sbin/nologinsystemd-bus-proxy:x:999:997:systemd Bus Proxy:/:/sbin/nologinsystemd-network:x:192:192:systemd Network Management:/:/sbin/nologindbus:x:81:81:System message bus:/:/sbin/nologinpolkitd:x:998:996:User for polkitd:/:/sbin/nologinlibstoragemgmt:x:997:995:daemon account for libstoragemgmt:/var/run/lsm:/sbin/nologinrpc:x:32:32:Rpcbind Daemon:/var/lib/rpcbind:/sbin/nologintss:x:59:59:Account used by the trousers package to sandbox the tcsd daemon:/dev/null:/sbin/nologinntp:x:38:38::/etc/ntp:/sbin/nologinabrt:x:173:173::/etc/abrt:/sbin/nologinpostfix:x:89:89::/var/spool/postfix:/sbin/nologinsshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologinchrony:x:996:994::/var/lib/chrony:/sbin/nologintcpdump:x:72:72::/:/sbin/nologindockerroot:x:995:992:Docker User:/var/lib/docker:/sbin/nologinsaslauth:x:994:76:Saslauthd user:/run/saslauthd:/sbin/nologinmailnull:x:47:47::/var/spool/mqueue:/sbin/nologinsmmsp:x:51:51::/var/spool/mqueue:/sbin/nologin

代碼:

#/usr/bin/env python# -*- coding:utf-8 -*-# @time   :2018/1/25 22:11# @Author :FengXiaoqing# @file   :uidSort-Passwd.pyimport codecsfile = "passwd.txt"sortfile = "sortpasswd.txt"fileContext = []sortuid = []with codecs.open(sortfile,'wb') as fsort:    with codecs.open(file,encoding='utf-8') as f:        fileContext += f.readlines()        for line in fileContext:            sortuid.append(int(line.split(':')[2]))        sortuid.sort()        for uid in sortuid:            for line in fileContext:              if str(uid) == line.split(":")[2]:                print(line)                fsort.write(line.encode("utf-8"))


Python檔案管理、亂碼及對passwd檔案排序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.