Pythonのファイル操作


1、ファイルの読み書き
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time    : 2018/1/25 20:49
# @Author  : zhouyuyao
# @File    : demonWrite.py
# PyCharm 2017.3.2 (Community Edition)
# Build #PC-173.4127.16, built on December 19, 2017
# JRE: 1.8.0_152-release-1024-b8 amd64
# JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
# Windows 10 10.0
# Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) 
# [MSC v.1900 64 bit (AMD64)] on win32

if __name__== "__main__":
    filename = input("Please input the name of file:")
    f = open(filename,"w")     #            
    while 1:         # 1        
        context = input("Please input context('EOF' will close file): ")
        if context == "EOF":
            f.close()
            break
        else:
            f.write(context)
            f.write("
") fRead = open(filename) readContext = fRead.read() print("------------start-------------") print(readContext) print("-------------end--------------") fRead.close()

実行結果:
Please input the name of file:z.log
Please input context('EOF' will close file): hello
Please input context('EOF' will close file): the weather is cool
Please input context('EOF' will close file): you have wear more clothes
Please input context('EOF' will close file): EOF
------------start-------------
hello
the weather is cool
you have wear more clothes

-------------end--------------

2、ファイルの読み込み方法
import codecs

ENCODING = "utf-8"       #    
f = open("z.log",encoding=ENCODING)
print(f.name)            #    
print(f.readline())      #         
print(f.readlines())     #         

with codecs.open("z.log","r",encoding=ENCODING) as f:
    print(f.read())

3、コード問題
符号化:中国語の符号化をサポートする:utf-8,gbk,gb 2312
decode復号encode符号化
Python 2ではコードのコードヘッダを定義せず、コンテンツに中国語が表示された場合にエラーが表示されます.Pythonはデフォルトではコードファイルの内容をASCII符号化処理としていますが、ASCII符号化には中国語は存在しません.異常が投げ出されるからです.問題を解決する方法はPythonの道ファイルにどのような符号化形式を使用させるかであり、中国語で使用できる一般的な符号化はutf-8、gbk、gb 2312などであり、コードファイルの最前端に以下の内容を追加するだけでよい.# -*- coding:utf-8 -*-
Pythonトランスコードのプロセス:既存の符号化-->Unicode符号化-->目的符号化
pythonは自動的に中国語の文字列をUnicodeに復号し、gbkに符号化します.復号は辞書で行われるので、復号方式が指定されていない場合はsys、defaultencodingで指定された方式で復号します.方法一:s.decode("utf-8").encoding("gbk")4、ファイルの並べ替え
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time    : 2018/1/25 23:06
# @Author  : zhouyuyao
# @File    : sortUIDPasswd.py
# PyCharm 2017.3.2 (Community Edition)
# Build #PC-173.4127.16, built on December 19, 2017
# JRE: 1.8.0_152-release-1024-b8 amd64
# JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
# Windows 10 10.0
# Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) 
# [MSC v.1900 64 bit (AMD64)] on win32
import codecs

file = "passwd"
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 3の新しい特性はテキストとバイナリデータをより明確に区別し、テキストは常にUnicodeであり、strタイプで表され、バイナリはbytesタイプで表される文字列はencodeでバイトパケットに符号化することができ、バイトパケットはdecodeで文字列に復号することができる.