如何修改python代码将转换后的文件移动到单独的文件夹?

时间:2018-02-23 03:18:50

标签: python python-3.x pandas

我有python代码将多个.xlsx文件转换为.csv。但它将它们放在同一个文件夹中。 如何修改此代码以确保将.csv文件放到单独的文件夹中?

import pandas as pd
import glob
excel_files = glob.glob('C:/Users/username/Documents/TestFolder/JanuaryDataSentToResourcePro/*.xlsx') # assume the path
for excel in excel_files:
    out = excel.split('.')[0]+'.csv'
    df = pd.read_excel(excel, 'ResourceProDailyDataset') # if the sheet name is always the same.
    df.to_csv(out) 

3 个答案:

答案 0 :(得分:1)

从文件名中拆分目录,然后为out提供一个新目录:

for excel in excel_files:
    folder = r'C:\ASeparateFolder\'
    out = folder + excel.split('\\')[-1].split('.')[0]+'.csv'
    df = pd.read_excel(excel, 'ResourceProDailyDataset') # if the sheet name is always the same.
    df.to_csv(out)

注意我使用'\\'进行拆分,无论您是使用glob还是'\'作为初始excel_file目录,它似乎都是'/'的常见拆分点。

答案 1 :(得分:1)

首先拆分路径,删除您不想要的文件夹,然后将其替换为其他文件夹。

import pandas as pd
import os
import glob
excel_files = glob.glob('C:/Users/username/Documents/TestFolder/JanuaryDataSentToResourcePro/*.xlsx') # assume the path
# folder name for the converted csv files
different_folder = "csv_folder"
for excel in excel_files:
    # make a csv path
    csv_folder_path =  "\\".join(excel.split('\\')[:-1])+"\\"+different_folder+"\\"
    if not os.path.exists(csv_folder_path):
        # create it if it doesn't exist
        os.makedirs(csv_folder_path)
    # full path of the csv file
    out = csv_folder_path+excel.split('\\')[-1].split('.')[0]+'.csv'
    df = pd.read_excel(excel, 'ResourceProDailyDataset') # if the sheet name is always the same.
    df.to_csv(out) 

这将在其中包含Excel文件的所有文件夹中创建一个新文件夹csv_folder,并将转换后的csv文件放在此文件夹中。

答案 2 :(得分:0)

您可以更改控制输出文件的变量。试试这样的事情

(function(){
var app = angular.module("form",[]);
    app.directive('formDirective', function(){
    return{
        restrict: 'E',
        templateUrl: 'user-form-directive.html',
        scope: {
           users: '='
        },
        controller:['$scope', function($scope){
            this.newUser = {};

            this.addUser = function(){
                $scope.users.push(this.newUser);      //<-- users is not defined
                this.newUser = {};
            };
        }]
    };
});
})();

必须存在该目录才能使其正常工作。