【问题标题】:Increment file name TCL增量文件名 TCL
【发布时间】:2020-06-13 05:13:53
【问题描述】:

我的输入文件有 5 行,所有 5 行都打印到 1 个文件中。如何在放置期间打印一个文件中的每一行?如何增加现有文件名?

# Input file
1 2 3 4
1 3 4 5
2 3 4 5
1 2 3 4
set infile  [open "infile.txt" r]
set outfile [open "outfile.txt" w]
set count    0

     while {[gets $infile line] > 0} {
        incr count

          puts $outfile"$count" "I want to split the input file into 4 different files. Each file is one line"      
    }

好像TCL不喜欢上面的语法?我希望得到outfile1,outfile2.....

【问题讨论】:

    标签: file-io tcl filenames


    【解决方案1】:

    如果你打算写入不同的文件,文件名应该不同。这就是$count 要去的地方。在您当前的代码中,$outfile 不是文件,而是文件的 channel identifier

    例如,您可以做的事情是:

    set infile  [open "infile.txt" r]
    
    set count    0
    
    while {[gets $infile line] > 0} {
        incr count
    
        set outfile [open "outfile$count.txt" w]
        puts $outfile $line
        close $outfile
    }
    
    close $infile
    

    这将创建文件outfile1.txt .. outfile5.txt

    【讨论】:

      【解决方案2】:

      当你这样做时:

      set outfile [open "outfile.txt" w]
      

      一个文件句柄outfile 与“outfile.txt”相关联,打开以供写入。此文件句柄将与打开的文件保持关联,直到它 已经关了。如果要输出到其他文件,则必须打开该其他文件 文件并将文件句柄分配给变量。

      就您的问题而言,您需要打开输出文件 在while 循环内。

      【讨论】:

      • 同意。此外,请使用“outfile$count”而不是 $outfile“$count”。并且不要忘记最后关闭文件,否则创建的文件可能是空的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-28
      • 1970-01-01
      • 1970-01-01
      • 2012-09-26
      • 2022-08-19
      • 1970-01-01
      • 2011-06-29
      相关资源
      最近更新 更多