Read and write files
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()
Results:
File method
Print (Fd.name) #打印文件名字
Print (Fd.mode) #打印模式 (r,w,a,a+)
The garbled problem of Python2
There is no garbled problem in Python3.
Coding
Chinese-supported encoding: Utf-8, GBK, gb2312
Decode decoding
Encode encoding
If you don't write the Python code, you'll get an error.
s = "hahaha"
Print (s)
This code file is executed with an error, which is a coding problem. Python defaults to the contents of the code file as ASCI encoding, but no Chinese is present in the ASCI encoding, so an exception is thrown.
The way to solve the problem is to let Python know what encoding is used in the file, for Chinese, the common encoding can be used UTF-8,GBK and gb2312, etc. Just add the following at the front of the code file:
#--Coding:utf-8--
Python to sort passwd files
Read and write files, file methods, Python2 garbled problem, Python to sort passwd files