From the second version of Python's core programming, this essay is just for the sake of making a deeper impression.
Environment OS X python version 2.7.10
1 #!/usr/bin/env python2 #--*--coding:utf-8--*--3 4 'maketextfile.py--Create text file'5 6 ImportOS7ls =Os.linesep8FName ='Test'9 #get filenameTen whileTrue: One ifos.path.exists (fname): A Print "ERROR: '%s ' already exists"%fname - Else: - Break the - #Get file content (text) lines -all = [] - Print "\nenter lines ('. ' by itself to quit). \ n" + - #Loop until user terminates input + whileTrue: AEntry = Raw_input ('>') at ifEntry = ='.': - Break - Else: - all.append (Entry) - - #write lines to file with proper line-ending inFobj = open (fname,'W') -Fobj.writelines (['%s%s'% (X,ls) forXinchAll ]) to fobj.close () + Print 'done!'
Run results
Core tip: Replace module variables with local variables
A name like OS.LINESEP requires an interpreter to do two queries (1) to find the OS to confirm that it is a module (2) to find the LINESEP variable in this module. Because the module is also a global variable, we consume more system resources
If you frequently use a property, it is recommended that you take a local variable alias for the property. Variable search speed will be much faster!
Os.path.exists () is a function in the OS module that returns False when a file name that does not exist is entered.
Fobj.writelines (['%s%s in all ]) This structure is called List parsing.
'%s%s ' adds a line terminator for each line, (X,LS) represents each line and its line terminator, which is ' \ n ' for a DOS or WIN32 for the UNIX platform ' \ r \ n '
By using OS.LINESEP we do not need to consider what platform the program is running on, nor do we need to decide which line terminator to use based on the platform. The File Object WriteLine () method receives a list of results that contain a terminator and
Its write file
Read File operation
1 #!/usr/bin/env python2 #--*--coding:utf-8--*--3 'readtextfile.py--Read and display text file'4 5 #get filename6fname = Raw_input ('Enter FileName:')7 8 #attempt to open file for reading9 Try:TenFobj = open (fname,'R') One exceptioerror,e: A Print "* * * File Open error:", E - Else: - #Display contents to the screen the forEachlineinchFobj: - PrintEachline, - fobj.close () -
Raw_input () Gets the file name entered by the user
Open file, read with For loop and show simple stuff ...
Python file Operations