Zeyu Xu

Let's enjoy AI and remote sensing!

Useful file operations in Python

1、Determine if the folder exists, and if it does not exist, create. import osif not os.path.exists(path):os.mkdir(path) 2、Traversing folders with files in a specific format. import osimport fnmatchimg_list = fnmatch.filter(os.listdir(path), '*.png')for img in img_list :…… 3、Rename the file. import osos.rename(Old_Dir,New_Dir) 4、Path connection. import osNew_Dir=os.path.join(path,filestr,filetype) 5、Copy files. import shutilshutil.copy(Old_Dir, New_Dir) 6、Replace the suffix name jpg_img=files[:-4]+".jpg" 7、Replace characters […]

1、Determine if the folder exists, and if it does not exist, create.

import os
if not os.path.exists(path):
os.mkdir(path)

2、Traversing folders with files in a specific format.

import os
import fnmatch
img_list = fnmatch.filter(os.listdir(path), '*.png')
for img in img_list :
……

3、Rename the file.

import os
os.rename(Old_Dir,New_Dir)

4、Path connection.

import os
New_Dir=os.path.join(path,filestr,filetype)

5、Copy files.

import shutil
shutil.copy(Old_Dir, New_Dir)

6、Replace the suffix name

jpg_img=files[:-4]+".jpg"

7、Replace characters in path

new_files=files.replace('_','')