File system operation (OS module)
1 ImportOS2 3file_name ="D:\\test_data\\1.txt"4file_name_2 ="D:\\test_data\\3.txt"5 #Deleting Files6 #Os.remove (file_name)7 8 #file Rename9 #os.rename (file_name, file_name_2)Ten One #Delete Empty directory ADir_name ='d:\\test_data\\1' - #os.removedirs (dir_name) - theDIR ='d:\\test_data\\1' - #gets the list of files in the specified directory -File_lists =Os.listdir (dir) - Print("gets the list of files in the specified directory:", file_lists) + #Get file creation time -File_time = Os.path.getmtime (dir +"\\"+ file_lists[-1]) + Print("file creation time:", File_time) A #determine if the file is a directory atFile_is_dir = Os.path.isdir (dir +"\\"+ file_lists[-1]) - Print("whether the file is a directory:", File_is_dir) - #assembly file Full path -File_path = Os.path.join (dir, file_lists[-1]) - Print("full path to the file:", File_path) - #Get File Size inFile_size =os.path.getsize (File_path) - Print("File Size:", file_size)
Operation Result:
1 Get the list of files in the specified directory: ['2-1'2-1.txt'2-2 '2-2.txt'2 files created: 1500290284.2089198 3 whether the file is a directory: False 4 file's full path: D:\test_data\1\2-2.txt5 File Size: 3
File traversal:
- Traverse directory all files including subdirectories
- Os.walk function: Recursively traverse directory files and subdirectories, parameters (directories to traverse, sort =ture to order)
- Returns three values: current directory, directory list under current directory, and list of files in current directory
1 forFile_path, dirs, File_namesinchOs.walk (Dir_name, topdown=True):2 Print("----------------------------------")3 Print("formerly:", File_path, dirs, File_names)4 forfile_nameinchFile_names:#Traverse List of file names5 Print("-"* 20)6 Print("file path under directory:", Os.path.join (File_path, file_name))7File_name_temp = Os.path.join (File_path, file_name)#assemble the full file name, including the path8List = File_path.split ("\\")#segmenting file names for easy access to parent directory names9 Print("File parent directory name:", List[-1])
Operation Result:
1----------------------------------2Formerly: D:\1 ['2-1','2-2'] ['2-1.txt','2-2.txt']3----4File path under directory: D:\1\2-1. txt5File parent directory Name: 16----7File path under directory: D:\1\2-2. txt8File parent directory Name: 19----------------------------------TenFormerly: D:\1\2-1 ['3-1','3-2'] ['3-1.txt'] One---- AFile path under directory: D:\1\2-1\3-1. txt -File parent directory Name: 2-1 ----------------------------------- theFormerly: D:\1\2-1\3-1 [] ['4-1.txt'] ----- -File path under directory: D:\1\2-1\3-1\4-1. txt -File parent directory Name: 3-1 +---------------------------------- -Formerly: D:\1\2-1\3-2 [] [] +---------------------------------- AFormerly: D:\1\2-2 [] []
Python file system operation (OS module)