Last curly brace kept being written on new line

Question:

So i have a .txt data like this :

215951.113,9121874.519,0
215963.471,9121913.567,0
216613.129,9115925.135,0
...

And i want to write it in this format :

    Point(1) = {219755.549,9129790.905,0} 
    Point(2) = {219754.857,9129793.278,0}
...

I made this kind of script :

f = open("D:\TAInput DataCoastlinegarpan_test.txt")
o = open("D:\TAInput DataCoastlinegarpan_test.geo","w+")
i = 1

for line in f :
    o.write(f"Point({i})= {{line}}")
    i=i+1

But instead it writes like this :

Point(1)= {219755.549,9129790.905,0
}Point(2)= {219754.857,9129793.278,0
}Point(3)= {219754.339,9129794.972,0
...
}Point(n)= {x,y}

I knew there is something wrong with the double curly brackets but i can’t seem to find the same topic that explains it..
Any help is appreciated!

Asked By: Aldwin Valdemar

||

Answers:

For the brackets

  • {{ and }} to print literal brackets, as your are in a f-string
  • {line} to print line value

For the line construction

  • there is a newline char at the end of each line, that you need to remove,
  • add a newline char at the end to go next line
  • add a tabulation at the beginning to get the expected output

For the code

  • use with statement for files, it auto-closes them
  • use enumerate to generate the i value

with open("garpan_test.txt") as f_in, open("garpan_test.geo", "w") as f_out:
    for i, line in enumerate(f_in, 1):
        f_out.write(f"tPoint({i}) = {{{line.rstrip()}}}n")

# OUT
Point(1) = {215951.113,9121874.519,0}
Point(2) = {215963.471,9121913.567,0}
Point(3) = {216613.129,9115925.135,0}
Answered By: azro

You can do like this:

I have used a list of strings to reproduce your problem.

x = ['215951.113,9121874.519,0', '215963.471,9121913.567,0']

with open('garpan_test.geo', 'w') as f:
    for i,v in enumerate(x,1):
        f.write(f'Point({i}) = { {v} }n') 

Contents of the file

Point(1) = {'215951.113,9121874.519,0'}
Point(2) = {'215963.471,9121913.567,0'}
Answered By: Ram
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.