[英]Copy all .csv files in a directory of folders to one folder in python
[英]Python: Copy identical .csv files from various folders (each folder has one .csv file) into a single folder
在我的問題中,文件系統設計如下:
Main folder -> sub-folder -> data.csv
這里, Main folder
有幾個子文件夾,每個sub-folder
都有一個data.csv
文件(請注意,每個子文件夾中的data.csv
文件與.csv
文件具有相同的文件名)。 對於數據處理,我需要將所有.csv
文件放在一個文件夾中,以便我可以使用以下代碼(以下代碼在我手動復制和重命名時有效(因為所有.csv
文件具有相同的名稱)每個.csv
文件從子文件夾到單個文件夾)。 在重命名.csv
文件時,我使用了子文件夾的名稱,例如:如果子文件夾命名為a1
,我將這個子文件夾內的.csv
文件重命名為a1.csv
import pandas as pd
import csv
import glob
import os
path = r'C:\Santobedi' # file path to the folder that contains manually copied and uniquely named .csv files
all_files = glob.glob(path + "/*.csv")
print(all_files)
for file in all_files:
file_name = os.path.split(file)[-1]
file_name_path = os.path.join('C:\Santobedi\CNN' + file_name)
transpose_df = pd.read_csv(file).T
transpose_df.to_csv(file_name_path)
手動復制和重命名大文件很煩人。 我想在一個 go 中做到這一點。 我怎么能用 Python (熊貓)做到這一點?
import os
import shutil
MAIN_FOLDER = 'main_folder'
for item in os.listdir(MAIN_FOLDER):
if os.path.isdir(os.path.join(MAIN_FOLDER, item)):
source = os.path.join(MAIN_FOLDER, item, 'data.csv')
destination = os.path.join(MAIN_FOLDER, f'{item}.csv')
shutil.move(source, destination)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.