![](/img/trans.png)
[英]Running python code on multiple files in folder and writing them to separate files
[英]How to modify python code to move converted files to a separate folder?
我有將多個.xlsx文件轉換為.csv的python代碼。 但這會將它們放入同一文件夾中。 如何修改此代碼以確保將.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)
從文件名拆分目錄,然后給你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)
請注意,我使用'\\\\'
進行拆分,無論您是在初始excel_file目錄中使用'\\'
還是'/'
,這似乎都是glob
的常見拆分點。
首先,分割路徑,刪除不需要的文件夾,然后將其替換為其他文件夾。
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文件將放置在此文件夾中。
您可以更改控制輸出文件的變量。 試試這個
out = 'some_directory/' + excel.split('.')[0]+ '.csv'
該目錄必須存在才能正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.