Python file operations

Source: Internet
Author: User
Tags fread

1. Read and Write files

  #!/usr/bin/env python#-*-coding:utf-8-*-# @Time: 2018/1/25 20:49# @Author: zhouyuyao# @File: Demon write.py# pycharm 2017.3.2 (Community Edition) # Build #PC -173.4127.16, built on December, 2017# jre:1.8.0_152-release- 1024-b8 amd64# jvm:openjdk 64-bit Server VM by JetBrains s.r.o# Windows 10.0# Python 3.6.1 (V3.6.1:69C0DB5, Mar 21 201  7, 18:41:36) # [MSC v.1900-bit (AMD64)] on win32if __name__== ' __main__ ': filename = input ("Please input the name of File: ") F = open (filename," w ") # Opens a file in write form while 1: # 1 Efficiency is the highest context = input (" Please input            Context (' EOF ' would close file): "If context = =" EOF ": F.close () Break Else: F.write (context) f.write ("\ n") 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 ' would close file): Hello
Please input context (' EOF ' would close file): The weather is cool
Please input context (' EOF ' would close file): You has wear more clothes
Please input context (' EOF ' would close file): EOF
------------Start-------------
Hello
The weather is cool
You are wear more clothes

-------------End--------------

2. Read File method

import codecsENCODING = "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. Python Coding issues

Coding:
Chinese-supported encoding: utf-8,gbk,gb2312

Decode decoding
Encode encoding

In the Python2 code is not defined in the queue, the content of the Chinese language will be error.
Python defaults to code file content as ASCII encoding, but ASCII encoding does not exist in Chinese because an exception is thrown.
The way to solve the problem is to make the Python path file use what encoding form, for Chinese, can use the common encoding has UTF-8,GBK and gb2312, and so on, just add the following content in the front of the code file:

# -*- coding:utf-8 -*-

The process of Python transcoding:
Original code--Unicode encoding--purpose encoding

Python automatically decodes the Chinese string into Unicode and then encodes it into GBK, because the decoding is done in a dictionary, and if it is not specified, it is decoded in the way indicated by sys,defaultencoding.
Method One:
s.decode("utf-8").encoding("gbk")

4. Python to sort passwd files

  #!/usr/bin/env python#-*-coding:utf-8-*-# @Time: 2018/1/25 23:06# @Author: zhouyuyao# @File: Sortu idpasswd.py# pycharm 2017.3.2 (Community Edition) # Build #PC -173.4127.16, built on December, 2017# Jre:1.8.0_152-relea Se-1024-b8 amd64# jvm:openjdk 64-bit Server VM by JetBrains s.r.o# Windows 10.0# Python 3.6.1 (V3.6.1:69C0DB5, Mar 21  18:41:36) # [MSC v.1900-bit (AMD64)] on win32import codecsfile = "passwd" sortfile = "sortpasswd.txt" Filecontext = []sortuid = []with codecs.open (Sortfile, "WB") as Fsort:with Codecs.open (file,encoding= "Utf-8") as F:fileconte XT + = 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"))  

The new features of Python3 make a clearer distinction between text and binary data,
Text is always Unicode, denoted by the STR type,
Binary is represented by the bytes type
Strings can be encode encoded into byte packets, while byte packets can be decode decoded into strings

Python file operations

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.