9 must-know ways to manipulate files/folders in Python

In recent years, with the increasing popularity of Python , people gradually use this programming language to perform some automated operations in order to save the inefficiency caused by repetitive labor, so it will definitely involve the operation of the file system , including file addition, Delete, modify, check, etc. Today, Xiaocai will introduce how to use Python to achieve these functions

output current path

We can get the location of the current file through the OS library in Python

import os
os.getcwd()

concatenation of paths

We do this through the os.path.join() method

os.path.join('output', 'Book1.xlsx')

output

output\Book1.xlsx

Check if a folder or file exists

Let's first look at how to confirm whether the folder exists, also through the OS module

os.path.exists('directory_name')

In the same way, if we check to see if a file exists, we can do this

os.path.exists('path/file_name')

create folder directory

Then let's see how to create a new folder

os.mkdir("文件夹名称")

Of course, if the folder directory already exists in advance, the above code will naturally report an error, so we usually check whether it already exists first.

if not os.path.exists('文件夹名称'):
    os.mkdir('文件夹名称')

Of course, we sometimes need to create subfolders under the already built folders, such as the following figure

insert image description here
At this time, it may be a bit cumbersome to refer to the os.mkdir() method. At this time, we can use the os.mkdirs() method to achieve

os.makedirs(os.path.join('test_dir', 'level_1', 'level_2', 'level_3'))

List all files contained in the current directory

code show as below

os.listdir('文件夹名称')

But sometimes we may want to search for files ending with "py" in all files in the current directory, for example, we can achieve this through wildcards, the code is as follows

list(glob(os.path.join('.', '*.py')))

The glob module mentioned above can quickly find the directories and files we want, and it supports the four wildcard characters *, **, ?, []

move files

What if we want to move files under different directory folders? Here we introduce the shutil module in Python . Suppose we want to move several csv files in the current directory to the "test_dir" directory folder. The code is as follows

import shutil

for file in list(glob(os.path.join('.', '*.csv'))):
    shutil.move(file, 'test_dir')

copy file

When we want to copy files, we can also use the shutil module. For example, we want to copy several csv files in the "test_dir" directory folder to the "output" directory folder. The code is as follows

shutil.copy(os.path.join('test_dir', 'data.csv'), 'output')

In addition, we can also rename the pasted files, the code is as follows

shutil.copy(os.path.join('test_dir', 'data.csv'),
            os.path.join('output', 'data_2.csv'))

Delete Files

Let's take a look at how to delete files? The os.remove( ) method can complete the function of deleting files,

os.remove(os.path.join('output', 'data_2.csv'))

When we want to delete an entire directory folder, we can use the os.rmdir( ) method, of course, it is only limited to empty directory folders

os.rmdir(os.path.join('test_dir', 'level_1', 'level_2', 'level_3'))

For the files that exist in the directory folder, it is not an empty directory folder, we still need to use the shutil module, the code is as follows

shutil.rmtree("test_delete")

or

shutil.rmtree(os.path.join("test_delete", "test_1_delete"))

Create and unzip archives

When it comes to the content related to the operation of compressed packages, we have to say the zipobj module.

  • Create a zip

Here we are going to use the write( ) method in the zipfile module

file_lists = list(glob(os.path.join('.', '*.xlsx')))

with zipfile.ZipFile(r"我创建的压缩包.zip", "w") as zipobj:
    for file in file_lists:
        zipobj.write(file)
  • Read the file information in the compressed package

Implemented by the namelist( ) method in the zipfile module

with zipfile.ZipFile("我创建的压缩包.zip", "r") as zipobj:
    print(zipobj.namelist())

output

['Book1.xlsx', 'supermarkt_sales.xlsx']

You can see that the output is the several excel files we packaged last time.

  • Unzip the single file in the compressed package

Implemented through the extract( ) method in the zipfile module

dst = "output"

with zipfile.ZipFile("我创建的压缩包.zip", "r") as zipobj:
    zipobj.extract("Book1.xlsx",dst)

The purpose of the above code is to decompress the "Book1.xlsx" file in the compressed package to the "output" directory folder

  • Unzip all the files in the compressed package

It is implemented by the extractall( ) method in the zipfile module. The code is as follows

dst = "output"

with zipfile.ZipFile("我创建的压缩包.zip", "r") as zipobj:
    zipobj.extractall(dst)

Recommended reading

My cousin said that this Python scheduled task can earn 5,000 yuan. Do you believe me?

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326838320&siteId=291194637