首页 > 解决方案 > Python:如何创建循环遍历文件夹中的 csv 文件的代码

问题描述

我试图创建一个 python 代码,该代码转到我在笔记本电脑上创建的包含 csv 文件的文件夹,然后循环遍历所有 csv 文件,然后将它们全部放入用户指定的文件夹中。到目前为止,这就是我所得到的,我需要帮助来完成这段代码。我尝试运行此代码,但没有任何反应。如果有人有更简单的方法来创建这个代码,那也很棒。

import pandas as pd
import glob
path = r"C:\Users\Documents\Practicefolder1\*.csv"
for Tname in glob.glob(path):
    print(Tname)

标签: pythoncsvfor-loopdirectoryexport-to-csv

解决方案


Rename the files so that the file path reflects the appropriate directory.

import pandas as pd
import glob
import os

# The folder that the files will be moved to 
user_specified_folder = input('Please specify the folder to put the files in')

path = r'C:\Users\Documents\Practicefolder1\*.csv'

for Tname in glob.glob(path):

    # get the name of the file itself
    file_name = os.path.basename(Tname)

    # get a new file name for the new path
    new_file_name = os.path.join(user_specified_folder,file_name)

    # rename the file so that it is in the appropriate directory
    os.rename(Tname, new_file_name);

推荐阅读