Python Basic Learning code file and input/output

Source: Internet
Author: User
Tags save file
Import Osls = Os.linesepdef func1 (): filename = raw_input (' Enter file name: ') f = open (filename, ' W ') while True:        Alline = Raw_input ("Enter a line ('. ' To quit):") if alline! = '. ': F.write ("%s%s"% (Alline,ls)) Else:break f.close () def FUNC2 (): F = open (' E:\\thefile.txt ', ' w+ ') print F.tell () f.write (' th E line 1\n ') print F.tell () f.write (' the Line 2\n ') print F.tell () f.seek ( -12,1) print f.readline () prin T F.tell () F.seek (0,0) print f.readline () print F.tell () f.close () Import sysimport osdef func3 (): print ' Yo U is ', Len (sys.argv), ' arguments ' print ' There is ', str (SYS.ARGV) def FUNC4 (): For Tmpdir in (' e:\\ ', ' d:\\ '): I        F Os.path.isdir (Tmpdir): Break Else:print ' no directory available ' tmpdir = ' if tmpdir: Os.chdir (tmpdir) CWD = OS.GETCWD () print ' current directory ', CWD print ' Create example Directo Ry ' #os. mkdir (' exAmple ') #os. ChDir (' example ') CWD = OS.GETCWD () print ' New directory ', CWD print ' directory list ' Os.listdir (CWD) print ' Create Test file ' F = open (' Test ', ' W ') f.write (' test\n ') f.wri Te (' test\n ') f.close () print ' Update directory list ' Print Os.listdir (CWD) print ' Rename test        To Filetest ' #os. Rename (' Test ', ' filetest ') print ' update directory list ' Print Os.listdir (CWD) Path = Os.path.join (Cwd,os.listdir (CWD) [0]) print ' full file pathname ' Print path print ' Pathname,ba Sename ' Print os.path.split (path) print ' filename,extension ' Print os.path.basename (path) prin T Os.path.splitext (os.path.basename (path)) print ' Display file contents ' F = open (' Test ', ' R ') for EAC  Hline in F:print eachline f.close () print ' Delete test file ' os.remove (path) print ' Update directory list '        Print Os.listdir (CWD) os.chdir (os.pardir) print ' Delete Test directory ' Os.rmdir (' example ') print ' Done ' Def func5 (): Print Os.path.expanduser ("~") def func6 (): filename = raw_input (' Input file: ') F = Open (filename, ' R ') for Eachline in F:if not Eachline.strip (). StartsWith (' # '): Print eachlinedef func 7 (): filename = raw_input (' Input file: ') F = open (filename, ' R ') for Eachline in F:if not ' # ' in eachline[ 1:]: Print Eachline f.close () def func8 (): filename = raw_input (' Input file: ') line = Int (raw_input (' in Put line number: ')] f = open (filename, ' R ') for Eachline in F:if line:print eachline l INE-= 1 else:breakdef func9 (): filename = raw_input (' Input file: ') lines = open (filename, ' R '). Re Adlines () return Len (lines) import Osdef func10 (): ls = os.linesep with open (' E:\\tmp.txt ', ' A + ') as F:for        I in range (100):    F.write ("%s%s"% (I,ls)) with open (' E:\\tmp.txt ', ' R ') as F:num = 1 for eachline in F:if nu M%! = 0:print Eachline num + = 1 Else:go = raw_input (' Continu    E,press c to quit ') num + = 1 if go = = ' C ': Breakdef func11 (file1,file2): Alines = open (File1, ' r ') blines = open (file2, ' r ') row = 0 for (aline,bline) in Zip (alines,blines): Row + = 1 if aline = = Bline:pass Else:col = 0 Print row for (A, B) I n Zip (aline,bline): if a = = B:col + 1 Else:print Co L Alines.close () Blines.close () from Configparser import Configparserdef FUNC12 (): CP = Configparser () #print o S.path.join (' c:\\windows\\ ', ' Win.ini ') Cp.read (Os.path.join (' c:\\windows\\ ', ' Win.ini ')) for sections in Cp.sections ( ): #print Cp.items(section) for key in Cp.options (section): print ' [%s]-%s=%s '% (Section,key,cp.get (section,key)) Cp.add _section (' name ') cp.set (' name ', ' test ', +) F = open (Os.path.join ("e:\\", "test.txt"), ' a ') Cp.write (f) f.close () d EF FUNC13 (): prompt = "" "(s) avings (C) Heck (F) inancialmarket (D) eposit (E) Xitenter Your choice:" "" function = "" "(s) avin GS (d) Raw (b) Orrow (L) Oanenter your choice: "" "account = {' s ': ' Savings ', ' C ': ' Check ', ' f ': ' financial ', ' d ': ' Deposit '} fun  = {' s ': ' savings ', ' d ': ' Draw ', ' B ': ' Borrow ', ' l ': ' loan '} CF = Configparser () cf.read (' E:\\familyaccount.ini ') Enter = Raw_input (Prompt). strip (). Lower () [0] While true:if enter in ' SCFD ': print ' welcome%s bussness '% a            Ccount[enter].lower () section = account[enter] select = Raw_input (fun). Strip () [0].lower ()                If select in ' Sdbl ': print ' welcome%s bussness '% fun[select] key = Fun[select] Mokey = Int (raw_inpUT (' Enter amount of money<must be digit.>: ') ' Cancel = raw_input (' cancel,please press ' C ' ... \ n ') if Cancel = = ' C ': return False else:f = open (' E:\\familya Ccount.ini ', ' W ') Cf.write (f) f.close () elif Enter = = ' E ': return F Alse else:print ' Invalid operation,try again ' Import sysimport osdef calc (argument): if argument[1] = = ' + ': Return int (argument[0]) + int (argument[1]) elif argument[1] = = ' * ': Return int (argument[0]) * INT (        ARGUMENT[1]) elif argument[1] = = '-': Return int (argument[0])-int (argument[1]) elif argument[1] = = ' * ': return int (argument[0]) * * INT (argument[1]) elif argument[1] = = '/': Return int (argument[0])/int (argument [1]) #if __name__ = = ' __main__ ': if sys.argv[1:][0] = = ' print ': With open (' E:\\txt ', ' R ') as F:print F.rea D () Os.remove(' E:\\txt ') Else:with open (' E:\\txt ', ' W ') as F:f.write ("". Join (sys.argv[1:])) f.write (' \    n ') F.write ((Calc (sys.argv[1:])) f.write (' \ n ') def func14 (): Afile = raw_input (' Input file: ') bfile = raw_input (' Input file: ') with open (Afile, ' R ') as Af:with open (bfile, ' W ') as Bf:for Eachl Ine in Afile:bf.write (Eachline) with open (bfile) as Bf:print bf.read () Import osdef func            (): File = Raw_input (' Enter file: ') with open (file, ' R ') as Af:with open (' E:\\test.txt ', ' W ') as BF:                    For Eachline in Af:if len (eachline) > 80:alist = List (eachline)                         Count = Len (alist)/$ for I in range (count): Bf.write ("". Join (alist[:79)) Bf.write (' \ n ') alist = alist[79:] Bf.write ("". Join (Alist ) Else:                   Bf.write (eachline) bf.write (' \ n ') with open (' E:\\test.txt ', ' R ') as Bf:wit H Open (file, ' W ') as Af:for eachline in Bf:af.write (eachline) os.remove (' E:\\test.txt ') def c    Reatefile (): File = raw_input (' input filename: ') content = raw_input (' Input file content: ') F = open (file, ' A + ')    F.write (content) f.write (' \ n ') f.close () def viewfile (): File = raw_input (' input filename: ') strtemp = ' f = open (file, ' R ') for Eachline in f:strtemp = strtemp + eachline return strtempdef editfile (): File = Ra     W_input (' input filename: ') line = Int ("raw_input (' input line number: ')") newline = raw_input (' Input new line number: ') f = open (file, ' r ') lines = F.readlines () f.close () if line > Len (lines): Return False Lines[line -1] = newline f = open (file, ' W ') F.writelines (lines) f.close () def showmenu (): prompt = "" a) Create file (prompt for file name and any line of text This input) b) display the file (display the contents of the file to the screen) cEdit the file (prompt for the line to be modified and then let the user modify it) d) Save file E) Exit Please enter the operation options (A, B, C, D, E): "" While True:try:commnet = Raw_input (promp            T). Strip () [0].lower () except (keyboardinterrupt,eoferror): commnet = ' e ' if commnet = = ' A ':        CreateFile () elif commnet = = ' B ': Viewfile () elif commnet = = ' C ': Editfile () elif Commnet = = ' d ': pass elif commnet = = ' E ': Break else:continue#if _ _name__ = = ' __main__ ': # showmenu () def FUNC16 (): filename = raw_input (' Input file: ') Filech = raw_input (' Input fil E character: ') Countnum = 0 with open (filename, ' R ') as F:for eachline in F:countnum + = Eachline. Count (Filech) print ' character%s is count%d '% (filech,countnum) import randomdef Func17 (ch,countnum,length): First            Length = 0 num = [] While Firstlength-countnum:chara = Random.choice (xrange (255)) if ch = = Chara:      Continue  Else:num.append (Chara) firstlength-= 1 for I in Range (Countnum): Num.append (CH) New num = [] While length:i = Int (random.random () * length) newnum.append (Num[i]) del Num[i] L Ength-= 1 return newnumimport zipfiledef func18 (filename): With ZipFile. ZipFile (' E:\\hello.zip ', ' W ') as F:f.write (filename) def func19 (dirname): With ZipFile. ZipFile (' E:\\test.zip ', ' W ') as F:for root,dirs,files in Os.walk (dirname): F.write (Root) for File in Files:f.write (Os.path.join (root,file)) Import Timedef func20 (): filename = raw_input (' Zip file n Ame: ') print ' size:%.2f '% (float (os.stat (filename) st_size)/1024/1024), "MB" f = zipfile. ZipFile (filename, ' r ') print ' filename datetime size compresssize rate ' for info in f.infolist (): #t = Time.ct IME (time.mktime (Tuple (list (info.date_time) + [0,0,0])) #print '%s\t%s\t%d\t%d\t '% (info.filename,t,info.file_siZe, # info.compress_size) print info.filename,info.file_size,info.compress_s Ize f.close ()

The above is the Python Basic Learning Code of the file and input and output content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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.