我又被卡住了! 我的故事是:
我需要找到一个目录中不同文件夹中存在的名为“ tv.sas7bdat”的文件,并将找到的所有文件的内容保存到桌面上的单个excel文件中。使用我的实际代码,我可以获取该文件的所有路径,并将其内容传输到数据框。但是,我无法将所有数据框附加到一个Excel文件中。
在我的Excel中,我仅找到最后一个数据帧!!
这是我的代码
import pandas as pd
from sas7bdat import SAS7BDAT
import os
path = "\\"
newpath = "\\"
files = []
# r=root, d=directories, f = files
for r, d, f in os.walk(path):
for file in f:
if 'tv.sas7bdat' in file:
files.append(os.path.join(r, file))
lenf = range(len(files))
for f in files:
print(f)
for df in lenf:
with SAS7BDAT(f) as file:
df = file.to_data_frame()
print(df)
group =pd.concat([df], axis=0, sort=True, ignore_index = True)
df.to_excel(newpath + 'dataframes_tv.xlsx',index=False)
答案 0 :(得分:1)
您可能想使用shutil
模块,它允许您使用copytree
函数复制目录及其中的文件。示例:
import shutil
shutil.copytree('/path/to/source', 'path/to/destination')
答案 1 :(得分:1)
如果不想更改代码,则可以enumerate
通过从列表中获取第一个文件,将初始数据帧分配为一侧的占位符,enumerate
来拆分该过程。列表中的其余文件,以将所有其他数据帧附加到初始文件中
编辑
files
和 # save the first dataframe from 1st list element
df = SAS7BDAT(files[0]).to_data_frame()
# enumerate the list to access greater elements
for k, f in enumerate(files):
# from 2nd element onward
if k > 0:
with SAS7BDAT(f[k]) as file:
# append all elements to the 1st
df = df.append(file.to_data_frame())
group = pd.concat([df], axis=0, sort=True, ignore_index=True)
df.to_excel('dataframes_tv.xlsx', index=False)
列表中的代码片段
private MemoryStream GetFileIcon(string name, IconReader.IconSize size)
{
Icon icon = IconReader.GetFileIcon(name, size, false);
using (icon)
{
Bitmap bmp = icon.ToBitmap();
MemoryStream ms = new MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
ms.Seek(0, SeekOrigin.Begin);
return ms;
}
}
public bool ProcessRequest(IRequest request, ICallback callback)
{
Uri uri = new Uri(request.Url);
string fileName = uri.AbsolutePath;
if (uri.Host == "storage")
{
fileName = appPath + uri.Host + fileName;
if (File.Exists(fileName))
{
Task.Factory.StartNew(() =>
{
using (callback)
{
//var bytes = Encoding.UTF8.GetBytes(resource);
//stream = new MemoryStream(bytes);
FileStream fStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
mimeType = ResourceHandler.GetMimeType(Path.GetExtension(fileName));
stream = fStream;
callback.Continue();
}
});
return true;
}
}
if (uri.Host == "fileicon")
{
Task.Factory.StartNew(() =>
{
using (callback)
{
stream = GetFileIcon(fileName, IconReader.IconSize.Large);
mimeType = ResourceHandler.GetMimeType(".png");
callback.Continue();
}
});
return true;
}
return false;
}
public bool ReadResponse(Stream dataOut, out int bytesRead, ICallback callback)
{
//Dispose the callback as it's an unmanaged resource, we don't need it in this case
callback.Dispose();
if (stream == null)
{
bytesRead = 0;
return false;
}
//Data out represents an underlying buffer (typically 32kb in size).
byte[] buffer = new byte[dataOut.Length];
bytesRead = stream.Read(buffer, 0, buffer.Length);
dataOut.Write(buffer, 0, buffer.Length);
return bytesRead > 0;
}
}}