Read and write files, file methods, Python2 garbled problem, Python to sort passwd files

Source: Internet
Author: User
Tags readfile

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.