import os
# 用os.walk遍历文件;用.endswith判断文件后缀
dfs = pd.DataFrame()
for root, dirs, files in os.walk(r'C:\Users\ll\Desktop\pandas\excels'):
for file in files:
if file.endswith('.xlsx'):
# 构建绝对路径
file_name = os.path.join(root, file)
# print(file_name)
df = pd.read_excel(file_name)
# print(df)
dfs = pd.concat([dfs, df])
# print(dfs)
dfs.to_excel(r'C:\Users\ll\Desktop\new.xlsx')
用dir函数加上循环即可。比如将D:\ABC文件夹内的所有文件显示到A列,代码如下:
Sub 遍历所有文件()Dim Fn$, N%
Fn = Dir("D:\ABC\*.*")
While Fn <> ""
N = N + 1
Range("A" & N) = Fn
Fn = Dir
Wend
End Sub
答:执行"获取所有文件夹",按提示 *** 作。文件夹清单会显示在工作表的AB列中。
Sub 获取所有文件夹()Dim Directory As String
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = Application.DefaultFilePath & "\"
.Title = "请选择一个文件夹"
.Show
If .SelectedItems.Count = 0 Then
Exit Sub
Else
Directory = .SelectedItems(1)
End If
End With
Cells.ClearContents
Call RecursiveDir(Directory)
End Sub
Public Sub RecursiveDir(ByVal CurrDir As String)
Dim Dirs() As String
Dim NumDirs As Long
Dim Filesize As Double
Dim TotalFolders, SingleFolder
Cells(1, 1) = "目录名"
Cells(1, 2) = "日期/时间"
Range("A1:B1").Font.Bold = True
Set TotalFolders = CreateObject("Scripting.FileSystemObject").GetFolder(CurrDir).SubFolders
Cells(WorksheetFunction.CountA(Range("A:A")) + 1, 1) = CurrDir
Cells(WorksheetFunction.CountA(Range("B:B")) + 1, 2) = FileDateTime(CurrDir)
If TotalFolders.Count <> 0 Then
For Each SingleFolder In TotalFolders
ReDim Preserve Dirs(0 To NumDirs) As String
Dirs(NumDirs) = SingleFolder
NumDirs = NumDirs + 1
Next
End If
For i = 0 To NumDirs - 1
RecursiveDir Dirs(i)
Next i
End Sub
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)