【问题标题】:TCL ( import a file and want to read line by line )TCL(导入文件并想逐行读取)
【发布时间】:2018-10-02 11:15:42
【问题描述】:

我想逐行读取 cd.txt 中的值并将每个值视为变量。

# Damper Properties
set Kd 0.000001;

set Cd [open "CD.txt" r];

set ad 0.000001;

if [catch {open $CD.txt r} cd] { ; # Open the input file and check for error

  puts stderr "Cannot open $inFilename for reading"; # output error statement

} else {

  foreach line [[read $cd] \n] { ; # Look at each line in the file

    if {[llength $line] == 0} { ; # Blank line -> do nothing

      continue;

    } else {

      set Xvalues $line; # execute operation on read data

    }

  }

  close $cd; ; # Close the input file

}

# Define ViscousDamper Material

#uniaxialMaterial ViscousDamper $matTag $Kd $Cd $alpha

uniaxialMaterial ViscousDamper     1   $Kd  $Cd $ad

这有什么问题吗? cd.txt 中的值是十进制值。循环不工作。请帮忙。

【问题讨论】:

    标签: arrays list tcl


    【解决方案1】:

    这一行:

    foreach line [[read $cd] \n] { ; # Look at each line in the file
    

    缺少关键位。这个版本看起来更正确:

    foreach line [split [read $cd] \n] { ; # Look at each line in the file
    

    (我希望您所做的不仅仅是将Xvalues 设置为每个非空行,因为这本身不太可能有用。)

    【讨论】:

    • 是的兄弟!但是那个 CD.txt 逐行包含十进制值!我想把这个值一一拿来分析!!我是TCL不好的文科生
    【解决方案2】:

    您打开了错误的文件:

    set Cd [open "CD.txt" r];
    

    Cd 变量现在包含一个文件句柄,其值类似于“file3421”。然后你做

    if [catch {open $CD.txt r} cd] { ; # Open the input file and check for error
    

    您现在正尝试打开文件“file3421.txt”——我希望您会在此处收到“找不到文件”错误。

    另外,你应该支持表达式:

    if {[catch {open "CD.txt" r} cd]} { ...
    #..^............................^ 
    

    从文件中读取行的惯用方式是:

    while {[gets $cd line] != -1} { ...
    

    【讨论】:

    • 好兄弟!我将更改名称并尝试。我是一个文科学生,TCL不好,那个文本文件有多个十进制值,想在set cd的位置一个一个地解析!!!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-28
    • 1970-01-01
    • 1970-01-01
    • 2013-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多