首页 > 解决方案 > TCL(导入文件并想逐行读取)

问题描述

我想逐行读取 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 中的值是十进制值。循环不工作。请帮忙。

标签: arrayslisttcl

解决方案


您打开了错误的文件:

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} { ...

推荐阅读