【问题标题】:python equivalent of matlab code to generate data filepython相当于matlab代码生成数据文件
【发布时间】:2021-06-06 16:42:08
【问题描述】:

Matlab 代码

for i=1:N
        fprintf(fid,'%g 1 0 %g %g %g\n',i,coords(i,:));
    end
    fclose(fid);
end

Python 代码(由我转换)

for i in range ( 0 , N  ):
    fdata.write("%g 1 0 %g %g %g\n" % (coords(i,:)))

我收到以下错误。

File "<ipython-input-8-c5647c2ae12d>", line 44
    fdata.write("%g 1 0 %g %g %g\n" % (coords(i,:)))
                                                ^
SyntaxError: invalid syntax

【问题讨论】:

    标签: python matlab syntax


    【解决方案1】:

    您必须使用格式字符串。您无法使用该语法在 python 3.x 中写入文件。写入文件的语法是:

    with open("file.txt", "w") as f:
        f.write(f"{variable}") # this is called a format string where the variable can be any datatype
    

    如果您不打算写入文件,则使用 print(f"{variable}") 在 for 循环下打印到终端。

    这些链接可能对您有所帮助:Matlab to Python code linktool to covert Matlab code to Python codeLearn format string.

    【讨论】:

      猜你喜欢
      • 2011-01-09
      • 1970-01-01
      • 1970-01-01
      • 2011-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多