Python learning-stage comprehensive exercises 3. python Comprehensive Exercises
Python learning-comprehensive phase Exercise 3
Based on the previous class learning, do the following example exercises: operations that contain folders and files (do not read the code first, and try to write it first. The code is for reference only and there are multiple implementation methods)
1. directory file traversal (L2 directory structure)
1 ). use the folder simulation in the previous learning example; print the directory structure of the corresponding directory, which needs to be indented;. the first line prints the target directory B. the specific two-layer directory structure (a folder is appended with \), and the file is suffixed with a file name.
2) not only print the results, but save the preceding print content to the dir_demo.txt file in the current working directory,
Can download and decompress to d Disk: http://files.cnblogs.com/files/feeland/Python_shutil.rar
The results of the example are as follows:
1 #! /Usr/bin/config python 2 #-*-coding: UTF-8-*-3 4 import OS 5 def listdir (d, f): 6 d_list = OS. listdir (d) # list all files and directories in the directory 7 print (d) 8 f. write (d + '\ n') 9 10 for I in d_list: 11 filepath = OS. path. join (d, I) 12 if OS. path. isdir (filepath): # If filepath is a directory, all files under the directory are listed 13 print ('\ t' + I +' \ ') 14 f. write ('\ t' + I +' \ '+' \ n') 15 for li in OS. listdir (filepath): 16 print ('\ t \ t' + li) 17 f. write ('\ t \ t' + li +' \ n') 18 elif OS. path: # If filepath is a file, list the file name 19 print ('\ t' + I) 20 f. write ('\ t' + I +' \ n') 21 22 23 demo_dir = u "D: \ Python_shutil" 24 25 with open('dir_demo.txt ', 'w') as f: 26 listdir (demo_dir, f)Listdir
In this example, "\ t" is used to indicate indentation. Note that the file. write () function does not automatically wrap the line, and print will print the line feed.
2. In the D: \ demo2 folder, create five txt files. The names and txt contents are test1 and test2... test5, respectively.
1) check whether the D: \ demo2 folder exists. If yes, clear all the files in the folder (make sure there are no files you need). If not, create the folder.
2) create a txt file. The results of the example are as follows:
1 import OS, shutil, time 2 3 OS. chdir ("d :\\") 4 dir_name = u "demo2" 5 dir_abs = OS. path. join (OS. getcwd (), dir_name) 6 if OS. path. exists (dir_abs): 7 shutil. rmtree (dir_abs) 8 time. sleep (1) # It is best to add a wait time after the delete operation, otherwise the mkdir operation may report an error 9 OS. mkdir (dir_name) 10 OS. chdir (dir_abs) 11 12 for I in range (): 13 txt_name = "test1_02.16.txt ". format (I) 14 with open (txt_name, "w") as f: 15 f. write ("test {0 }". format (I ))Folder & txt