1 Introduction
File and folder operations in Python are still very important~
2 Working Directory Operation Code
Set the working directory:
First, you can check the working directory,
# 查看当前的工作目录
print(os.getcwd())
If the working directory is incorrect, you can use the os.chdir() function to modify it;
Traverse all sub-files in the folder (excluding grandchildren):
# 遍历当前文件夹的直接子文件
for file in os.listdir(root):
print(file)
3 File read and write
.txt file read and write
When writing multi-line list data into a .txt file, use the f.writelines() function, because the f.writelines() function is more efficient than the f.write() function ;
4 Folder operation code
Delete a folder
if os.path.isdir(dir):
shutil.rmtree(dir)
5 .csv file reading and writing