1. 程式人生 > >讀寫文件、文件方法、python2的亂碼問題、python對passwd文件進行排序

讀寫文件、文件方法、python2的亂碼問題、python對passwd文件進行排序

__main__ .com 哈哈 == nco star 9.png mar ges

讀寫文件
if __name__==‘__main__‘:
    filename=input(‘請輸入保存的文件:‘)
    fdfile=open(filename,‘w+‘)
    while 1:
        text=input(‘請輸入內容: ‘)
        if text == ‘EOF‘:
            break
        else:
            fdfile.write(text)
            fdfile.write(‘\n‘)
    fdfile.close()
    readfile=open(filename)
    print(‘##############start###################‘)
    print(readfile.read())
    print(‘##############end###################‘)
    readfile.close()

結果:
技術分享圖片

文件方法

技術分享圖片
print(fd.name) #打印文件名字
print(fd.mode) #打印模式 (r,w,a,a+)

python2的亂碼問題

在python3中不會出現亂碼的問題。
編碼
支持中文的編碼:utf-8, gbk, gb2312
decode 解碼
encode 編碼
不寫python代碼排頭,就會報錯。
s = "哈哈哈"
print(s)
這個代碼文件被執行時就會出錯,就是編碼出了問題。python默認將代碼文件內容當作asci編碼處理,但asci編碼中不存在中文,因此拋出異常。
解決問題之道就是要讓python知道文件中使用的是什麽編碼形式,對於中文,可以用的常見編碼有utf-8,gbk和gb2312等。只需在代碼文件的最前端添加如下:

#-- coding:utf-8 --

python對passwd文件進行排序

技術分享圖片

讀寫文件、文件方法、python2的亂碼問題、python對passwd文件進行排序