我正试图从Matlab进入Python,所以从小开始,我正在寻找读写数据。我已经被Matlab的优秀自包含文档所破坏,我很难找到最好的Python方法,因为Matlab主要使用fopen,textscan,fgetl,regexp和fprintf来实现。我见过一些提倡者numpy.loadtxt(& savetxt),而其他人提倡“用open(...)作为f:for line ...”的方法 - 后者可能是我在这个阅读案例中需要的一列字符串标题后跟一个浮点数矩阵,两者都是未知大小。我把样本Matlab代码放在一起:
其中一些步骤,例如2-3,可以在实践中结合使用,但在这里将它们分开将有助于我完成一些不同的任务。这可能更像是“请与我分享Python中针对此通用任务的最佳编码实践”,而不是一个非常具体的问题,但我希望这对其他新的Python用户也很有用。感谢任何特定的Python代码和/或引用。
%%
function ReadWrite()
tic
f=readPaths();
[t,n]=pullSize(f);
[hdr,d]=readData(f,t,n);
writeData(hdr,d);
toc
end
%%
function f=readPaths
fid=fopen('Paths.txt','r');
f=textscan(fid,'%s%s','delimiter','\t','headerlines',1);
fclose(fid);
f=char(fullfile(f{1},f{2}));
end
%%
function [t,n]=pullSize(f)
n=0;
fid=fopen(f,'r');
l=fgetl(fid);
h=isempty(regexp(l,',','once')); % headers are not comma delimited
while h
n=n+1;
l=fgetl(fid);
h=isempty(regexp(l,',','once'));
end
fclose(fid);
t=length(regexp(l,','))+1; % file is comma delimited
end
%%
function [hdr,d]=readData(f,t,n)
fid=fopen(f,'r');
hdr=textscan(fid,'%s',n);
d=textscan(fid,repmat('%f',1,t),'delimiter',',');
fclose(fid);
d=[d{:}];
hdr=[hdr{:}];
end
%%
function writeData(hdr,d)
fid=fopen('DataTest.csv','w');
for i=1:length(hdr)
fprintf(fid,'%s\n',hdr{i});
end
fprintf(fid,[repmat('%.4f,',1,size(d,2)-1),'%.4f\n'],d');
fclose(fid);
end
答案 0 :(得分:1)
这似乎是您可能想要使用Pandas库的东西。 Pandas有一个read_csv方法,它可以完全按照它的声音进行操作,并将数据存储在所谓的DataFrame中,您可以将其视为excel电子表格。
该功能类似于R的数据帧或data.table包。
答案 1 :(得分:1)
您可以在Python标准库中使用csv模块来执行此操作。
import csv
with open('path/to/file.csv', 'r') as f:
dict_reader = csv.DictReader(f)
with open('path/to/output.csv', 'w') as w:
dict_writer = csv.DictWriter(w, dict_reader.fieldnames)
dict_writer.writeheader()
dict_writer.writerows(dict_reader)
答案 2 :(得分:0)
谢谢大家。我最初使用csv模块和你建议的其他一些东西,但最终使用numpy的load [save] txt以及标准Python的readline和其他一些杂项库来处理某些事情。我今天刚刚回到这里,我花了一段时间才弄清楚嵌套函数,读/写格式等等,但我复制了代码,它只比我的Matlab版本慢了一点 - 包括后面的后代:< / p>
<li role="presentation"><a href="index.php">Home </a></li>
<li role="presentation"><a href="about.php">About Us</a></li>
<li role="presentation"><a href="contact.php">Contact Us</a></li>
<li role="presentation"><a href="gallery.php">Gallery</a></li>