Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

save .txt file

Status
Not open for further replies.

stewang

Programmer
Aug 21, 2003
77
0
0
NZ
Hello all:
In my application, I read a .txt and write to another .txt file.
But I 'd like to do some change for my application.

The first one is that I want bring out a dialog box
for save file instead of the default .txt name. I tried to use the command of
"set $thefile [tk_getSaveFile] instead of the command "set thefile [open "sorted2.txt" w]",
but it does nothing.

Another problem is how to insert a string to the end of the file, if the string already
exist, I don't need to insert to the file.
For example, I got a "data.txt" file, and it contains the following datas.

steve,800
brian,400
tui,900
molly,930
keith,200
kim,500

And I want to insert two string of the "stewang, 100" and "steve,800" into .data.txt,
I like result like the following;

steve,800
brian,400
tui,900
molly,930
keith,200
kim,500
stewang,100

Could anyone help me,please.

Thanks
rgds
stewang

Code:
set thefile [open "data.txt" r]
set line [gets $thefile]
while {[eof $thefile] == 0} {
	puts $line
	set data [split $line ","]
	set key [lindex $data 0]
	set value [lindex $data 1]
	set myarray($key) $value
	set line [gets $thefile]
}
close $thefile
puts [array get myarray]
foreach key [array names myarray] {
	set value $myarray($key)
	set myarray($key) [expr $value/5.0]
}
puts [array get myarray]

set sum 0
foreach key [array names myarray] {
	set value $myarray($key)
	set sum [expr $sum + $value]
}
set mean [expr $sum/[array size myarray]]
puts $mean

set thelist {}
foreach key [array names myarray] {
	set value $myarray($key)
	lappend thelist [list $key $myarray($key)]
}
set thelist [lsort -index 1 -decreasing -real $thelist]
puts $thelist


# once we've created the list we can sort it in different ways
# here the sort key is the name, the first element in each sublist, index 0
# we are sorting ascii values
set thelist [lsort -index 0 -increasing -ascii $thelist]

# get a file handle. notice the w argument saying that we'll write to it
set thefile [open "sorted2.txt" w]
foreach item $thelist {
	set name [lindex $item 0]
	set score [lindex $item 1]
	puts $thefile "$name,$score"
}
close $thefile
 
Thanks you come to my question, I known the answer alredy
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top