Python Basic Text Read and write __python

Source: Internet
Author: User
Tags readfile string format

Today came across a requirement to read a TXT document that contains multiple lines of numbers, sort each line of numbers, and then write to a new TXT document. Although this demand is not difficult to solve, but in the actual processing process, encountered a lot of pits, recorded here for reference. 1. Read the text document:

As shown in the following illustration:
2. Implementation code:

#-*-Coding:utf-8-*-
"" "
Created on Tue Mar 19:48:58 2017 @author: Zch" "" "",
Read more from the A.txt file Row numbers, sorted in units of behavior, are written to the B.txt file
"" "

def ReadFile ():
    data = []
    f = open (' c:\\users\\administrator\\ Desktop\\a.txt ')
    #读入多行数字, first convert the read string format number to int by using the map function,
    #然后将数字list化, add to the data, and form a two-dimensional list of
    F.readlines ():
        data.append (List (Int,line.split (",")))
    print (data)
    f.close ()
    return Data

def writefile ():
    w = open ("C:\\users\\administrator\\desktop\\b.txt", "W")
    #构建一个for循环, The one-dimensional list in data is then sorted, and then the B.txt is written in the for-
    i in data:
        output = sorted (i)
        w.writelines (str (output) + "\ n")
        print (output)
    w.close ()

if __name__ = = ' __main__ ':
    #readFile ()
    WriteFile ()
3. Write a new text document:

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.