SoFunction
Updated on 2024-11-17

Python directory and file handling summary in detail

1, determine whether the directory exists, determine whether the file exists, create a directory, rename the directory or file

import os

# Get current directory path: E:\Work\Projects\python
print(()) 

# Determine whether the current directory exists, if not, create the directory dir1
if not ('dir1'):
  ('dir1') 

# Determine whether the specified directory exists, if not, create the directory dir22
if not ('E:\Work\Projects\python\dir22'):
  ('E:\Work\Projects\python\dir22') 

# Determine if the specified file exists in the current directory
print((''))

# Rename directory dir22 to dir2 (rename can also be used for files)
('dir22', 'dir2')

# Switch to the directory dir2
('dir2')

# Switch to the directory dir2 and get the current directory path: E:\Work\Projects\python\dir2
print(())

2. Directory and file search

The current directory structure is

│ 
│ 
│ 
│
├─dir1
│ dir1_1.txt
│ dir1_2.txt
│
└─dir2

(1) Get a list of directories and files in the specified directory (excluding subdirectories)

import os
path = ()
for filename in (path):
  print((path,filename))
'''running result:
E:\Work\Projects\python\
E:\Work\Projects\python\
E:\Work\Projects\python\dir1
E:\Work\Projects\python\dir2
E:\Work\Projects\python\
'''

(2) Recursively get a list of directories and files (including subdirectories) in a given directory

import os

path = ()
#walk produces 3 tuples: directory path, directory name, filename
for dirpath,dirnames,filenames in (path):
  print("dirpath:{};dirnames:{};filenames:{}".format(dirpath,dirnames,filenames))

''' Run results:
dirpath:E:\Work\Projects\python;dirnames:['dir1', 'dir2'];filenames:['', '', '']
dirpath:E:\Work\Projects\python\dir1;dirnames:[];filenames:['dir1_1.txt', 'dir1_2.txt']
dirpath:E:\Work\Projects\python\dir2;dirnames:[];filenames:[]
'''

for dirpath,dirnames,filenames in (path):
  # Output all files
  for filename in filenames:
    print((dirpath, filename))
  # Output all directories
  for dirname in dirnames:
    print((dirpath, dirname))

'''running result:
E:\Work\Projects\python\
E:\Work\Projects\python\
E:\Work\Projects\python\
E:\Work\Projects\python\dir1
E:\Work\Projects\python\dir2
E:\Work\Projects\python\dir1\dir1_1.txt
E:\Work\Projects\python\dir1\dir1_2.txt
'''

3. Access to information on documents

import os
import time

filepath = r'E:\Work\Projects\python\'

# Split the path, return a tuple (directory, filename), result: ('E:\\Work\\\Projects\\\python', '')
print((filepath))

# Return to the directory section, result: E:\Work\Projects\python
print((filepath))

# Returns the filename, the result:
print((filepath))

# Returns the file size (in bytes), result: 1296
print((filepath))

# Returns the creation time, the last modification time, and the last access time of the directory or file (in seconds from January 1, 1970, New Era, to the time of access)
ctime = (filepath)
mtime = (filepath)
atime = (filepath)
# Example results: 1566436201.5443518 1566439077.5319004 1566439099.905073
print(ctime, mtime, atime)

#Converting Unix timestamps to time
def unix2time(unix):
  time_local = (unix)
  dt = ("%Y-%m-%d %H:%M:%S",time_local)
  return dt

# Convert Unix timestamps to time
#Examples of results: 2019-08-22 09:10:01 2019-08-22 09:57:57 2019-08-22 09:58:19
print(unix2time(ctime),unix2time(mtime),unix2time(atime))

4, directories and files to move, copy, delete

The current directory structure is

│ 
│ 
│ 
│
├─dir1
│ dir1_1.txt
│ dir1_2.txt
│
└─dir2
import shutil
#Copy the entire directory
('dir1','dir1_bak')

# Copy a single file, the second argument can be a directory or a file name.
('', 'dir2/1_bak.txt')
('', 'dir2')

# Move a directory or file
('dir1', 'dir2')
('', 'dir2')

# Delete the entire catalog
('dir1_bak')

This is the whole content of this article.