[SOLVED] How to access .txt file using tcl PROC function

Issue

This Content is from Stack Overflow. Question asked by Santhosh Nayak D.

I have two files and I am comparing specific lines between two files using the def function.

def readPinFile(filename): 

   result = None
   with open(filename, "r") as file:    

    result = {}
    lastPin = None        
    for line in file:
        lines = line.strip()
        
        if lines[:3] == "PIN": 
            lastPin = lines.split(" ")[1]               
            result[lastPin] = {"LAYER": None, "RECT": None}
        
        if lines[:5] == "LAYER":
            result[lastPin]["LAYER"] = lines.split(" ")[1]
           
        if lines[:4] == "RECT":
            result[lastPin]["RECT"] = lines.split(" ")

return result

pin_of_file1 = readPinFile("osi_hbmp_top_briscm_1.lef") #lef file1
pin_of_file2 = readPinFile("osi_hbmp_top_briscm_2.lef")#lef file2

The TCL code I tried to get the same output

proc fileinput {filename} {
set filedata [open filename r]
set file1 [ read $filedata ]
foreach line [split $file1 n] {
      set pindata { PIN { LAYER {} RECT {} }}
      if {[string match *PIN* $line]} {
          dict lappend pindata PIN $line         
         }
      if {[string match *LAYER* $line]} {
           dict lappend pindata PIN {LAYER{$line}} 
         } 
      if {[string match *RECT* $line]} {
           dict lappend pindata PIN {RECT{$line}}
          } 
      }
}
fileinput{osi_hbmp_top_briscm_1.txt}}
#fileinput{osi_hbmp_top_briscm_2.txt}}

When I am running my code I am getting errors like this
invalid command name “fileinput{osi_hbmp_top_briscm_1.txt}}”
while executing
“fileinput{osi_hbmp_top_briscm_1.txt}}”
(file “aa.tcl” line 18) line: fileinput{osi_hbmp_top_briscm_1.txt}}

can anyone tell me what wrong I did and how to clear that error?



Solution

The error trace tells you the immediate problem:

couldn't open "filename": no such file or directory                     
    while executing                     
"open filename r"                      
    (procedure "fileinput" line 2)

You need to give the name of the file, not the name of the variable containing the file name. Tcl cares about whether things are uses or references/names a lot. You fix this by using:

    set filedata [open $filename r]

in the procedure; the added $ is vital as it says "read from the variable and use its value here".


This Question was asked in StackOverflow by Santhosh Nayak D. and Answered by Donal Fellows It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?