1. Sort a list of numbers from small to large, then write to the file, then read the contents of the file from the file, and then reverse-order it in the next line appended to the file.
import codecsl1=[22,32,5,88,43,20,18,99,201,100,302]l2=[]print ' ********** sort ********** ' L1.sort () print l1print ' ********** write file.txt file ********** ' With codecs.open (' file.txt ', ' w+ ') as F1: for i in xrange (0,len (L1)): if i<len (L1) -1: f1.write (str (l1[i]) + ', ') else: f1.write (str (l1[i)) print ' Write file Success!!! ' With codecs.open (' file.txt ', ' r+ ') as f2: l2=f2.read (). Split (', ') print ' ********** reverse order * ' L2.reverse () print l2print ' ********** inserts the reverse order result into the file.txt file ********** ' With codecs.open (' File.txt ', ' a ') as f3: f3.write (' \ n ') for x In xrange (0,len (L2)): if x<len (L2) -1: f3.write (l2[x]+ ', ') else: F3.write (l2[x]) print ' Write file successfully!!! ‘
Operation Result:
Sort **********[5, 18, 20, 22, 32, 43, 88, 99, 100, 201, 302]********** write file.txt file ********** write file success!!! Reverse order **********[' 302 ', ' 201 ', ' 100 ', ' 99 ', ' 88 ', ' 43 ', ' 32 ', ' 22 ', ' 20 ', ' 18 ', ' 5 ']********** insert the reverse order result into the file.txt file * * * Write file Success!!! 5,18,20,22,32,43,88,99,100,201,302302,201,100,99,88,43,32,22,20,18,5
2. Write the string, list, tuple, dict to the file, respectively.
Import codecsstr= ' this is a string,now insert into the file.txt ' L1=[' This ', ' was ', ' a ', ' String ']t1= (' Insert ', ' into ', ' the ', ' file.txt ') d1={' Name ': ' File ', ' Type ': ' txt ', ' Context ': ' Dict '} With codecs.open (' file.txt ', ' a ') as f1: f1.write (' \ n ') print ' ******** write String ******** ' f1.write (str) f1.write ( ' \ n ') print ' ******** start writing to list ******** ' for x in xrange (0, len (L1)): if x<len (L1) -1: f1.write (l1[x]+ ', ') else: f1.write (L1[x]) print ' Write list success!!! ' f1.write (' \ n ') print ' ******** start writing tuples ********' for y in xrange (0, len (T1)): if y<len (T1) -1: F1.write (t1[y]+ ', ') else: f1.write (T1[y]) print ' write meta-group success!!! ' f1.write (' \ n ') print ' ******** start writing dictionary ******** ' for z in d1.iteritems (): for a in z: f1.write (A + ' ') print ' Write dictionary success!!! ‘
Operation Result:
Write String **************** start write list ******** write list success!!! Start writing tuples ******** write tuples successfully!!! Start writing dictionary ******** write dictionary success!!! This was a string,now insert into the file.txtthis,is,a,stringinsert,into,the,file.txttype txt Name file Context dict
This article is from the "Dreamscape" blog, make sure to keep this source http://dyqd2011.blog.51cto.com/3201444/1977840
Python Exercises (ii)