如何从python将文件从一个文件夹移动到另一个文件夹

2024-05-16 00:48:53 发布

您现在位置:Python中文网/ 问答频道 /正文

df1:

   Country   Product
0  Columbia  Shoes
1  Brazil    Football

folder1_files: 

col_sho.csv
Bra_foo.csv
Gha_cof.csv

fold1_path='c:/folder1'
fold2_path='c:/foder2'

我需要根据来自df1的信息将一些文件从文件夹1移动到文件夹2。您可以在df1中看到有两个国家和产品。根据该信息,col_shoe.csv和bra_foo.csv文件需要复制到folder2中


Tags: 文件csvpath文件夹信息foocolproduct
1条回答
网友
1楼 · 发布于 2024-05-16 00:48:53

使用清晰的文件名将有助于轻松移动文件

import shutil
import os
import pandas as pd
folder1 = "./folder1"
folder2 = "./folder2"


df = pd.DataFrame({"Country":["Columbia", "Brazil"], "Product":["Shoes","Football"]})
s = df["Country"].str[:3] + "_" + df["Product"].str[:3] + ".csv"
for file_name in s.values:
    if os.path.isfile(folder1 + os.path.sep + file_name):
        shutil.move(folder1 + os.path.sep + file_name, folder2 + os.path.sep + file_name)
    else:
        print("file {} is not available".format(file_name))

如果只想使用小写字母,则可以使用

df["Country"].str[:3].str.lower()

相关问题 更多 >