簡體   English   中英

循環並重命名文件

[英]Loop through and rename files

我正在嘗試遍歷一個文件夾,其中包含一堆標題為Spec01,Spec02,Speco03,...,Spec14的其他文件夾。 每個Spec文件夾都有一些文件,但我需要的文件在每個文件夾中都稱為samples.dat。 我想遍歷每個文件夾,將其轉換為Excel文件,並使用父文件夾的名稱保存,即Spec ##。

我的代碼中的pandas部分可以自行運行,但是當我添加for循環時,我最終只會得到一個名為[] .xlsx的文件。 我相信我的循環只是在寫自己

這是我正在使用的代碼


import pandas as pd
import os

your_path = 'C:/Users/abh85/Desktop/AAA/'
for root, dirs, files in os.walk(your_path):
    for subdir in files:
            if subdir.endswith('.dat'):
                with open(os.path.join(root, subdir)) as f1:
                    #change skiprow as needed
                    df = pd.read_csv(f1, sep='\s+', skiprows = 4, error_bad_lines = False) 
                    df = df.apply(pd.to_numeric, errors ='coerce')
                    df = df.dropna() #drop blank rows from coerce process
                    #manually change column names per test data acquisition
                    df.columns = ['Time (s)', 'Displacement (mm)', 'ExDisp (mm)', 'CMOD (mm)', 'Force (kN)']
                    df.to_excel('C:/Users/abh85/Desktop/xls/%s.xlsx' %dirs, index=False)

我知道重命名不起作用,因為我在循環中調用“dirs”。 下面的代碼給了我想要的名字,但我不知道如何合並它:

import os 

your_path = 'C:/Users/abh85/Desktop/AAA/'
for path, dirs, files in os.walk(your_path):
    for name in dirs:
        print(name)

我可以上傳帶有示例文件夾的zip。

所以,我想出了這個。 我仍然是Python的新手,所以我不確定這是否是最有效的答案,但它似乎可以做到這一點:

import os

your_path = 'C:/Users/abh85/Desktop/AAA/'
file_names = []

i = 0

for root, dirs, files in os.walk(your_path):
    for name in dirs:
        file_names.append(name)


    for subdir in files:
            if subdir.endswith('.dat'):
                with open(os.path.join(root, subdir)) as f1:
            #change skiprow as needed
                          df = pd.read_csv(f1, sep='\s+', skiprows = 4, error_bad_lines = False) 
                          df = df.apply(pd.to_numeric, errors ='coerce')
                          df = df.dropna() #drop blank rows from coerce process
            #manually change column names per test data acquisition
                          df.columns = ['Time (s)', 'Displacement (mm)', 'ExDisp (mm)', 'CMOD (mm)', 'Force (kN)']
                          df.to_excel('C:/Users/abh85/Desktop/xls/%s.xlsx' %file_names[i], index=False)
                          i += 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM