Using the VIM editor, first create a new py file: Vim print_filename.py
1. Read all files and directory names in the specified directory print_filename.py
#-** Coding:utf-8-*-//note, prompting for an editor environment with Unicode encoding support
Improt OS//reference OS module
Print Os.listdir ("/users/baolinfang")//Read all files and directories in/users/baolinfang
2. Read all the file/directory information in the specified directory print_allfilename.py
#-** Coding:utf-8-*-//note, prompting for an editor environment with Unicode encoding support
Improt OS//reference OS module
For Root,dirs,files in Os.walk ("/users/baolinfang"):
Print Root,dirs,files//note in the Loop to indent
3. Save the output file/directory as a file
#-** Coding:utf-8-*-//note, prompting for an editor environment with Unicode encoding support
Improt OS//reference OS module
For Root,dirs,files in Os.walk ("/users/baolinfang"):
Open (' MYFILENAME.CDC ', ' a '). Write ("%s%s"% (root,dirs,files))//Get a MYFILENAME.CDC file, now open, wait until later to answer.
Practice:
1. Other functions of OS module:
A, Os.system () run the shell command
>>> Os.system ('dir') 0>>> os.system ('cmd ' # Boot dos
B, Os.path.join (path,name): Connection directory and file name or directory
>>> os.path.join ('c:\\python','a.txt') ' C:\\python\\a.txt '>>> os.path.join ('c:\\python','F1 ' )'c:\\python\\f1'
Other reference http://www.cnblogs.com/BeginMan/p/3327291.html
2, open () mode:
' R ' read mode, ' W ' write mode, ' a ' append mode, ' B ' binary mode, ' + ' read/write mode
Python File write operation:
>>>f = open ('a.txt'w') # Open A.txt in writing and assign a value to the variable F>>>f.write ('Hello,') # Write () content within >>>f.write ('iplaypython') # in Hello , followed by write Iplaypython>>>f.close () # Close
Python file read operation:
In order to read the file operation, only need to change the mode to ' r ' can, or the mode is empty do not write parameters, but also the meaning of reading, because the program by default is ' R '.
>>>f = open (' A.txt ', ' R ')
>>>f.read (5)
' Hello '
Read () is a method of reading a file, the number of characters to be read in parentheses, the number of characters filled in here is 5, if the fill is 1 then the output should be ' H '.
There are some common techniques for file reading, like the following two types:
1. Read (): reads all content
2, ReadLine (): Read line by row
To be continued .....
Python learning, the cute Python first article