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: