I was wondering what I am doing wrong. I'm writing a python program that converts my "joke-made" programming language into python. I always get this weird mess. This is my code
#input file
inputfile = input("Filename > ")
print("""
Available Languages:
Python
""")
langsel = input("Select > ")
fin = open(f"{inputfile}", "rt")
#output file to write the result to
fout = open(f"{inputfile}.py", "wt")
#for each line in the input file
if langsel == "Python":
for line in fin:
fout.write(line.replace('printiln(', 'print('))
fout.write(line.replace('rinput(', 'input('))
fout.write(line.replace('printiln("', 'print("'))
fout.write(line.replace("printiln('", "print('"))
else:
print("Invalid Language")
#close input and output files
fin.close()
fout.close()
I used this file as a test:
printiln("Are you sure? ")
rinput("Yes or No? ")
Python puts out this file when running the program:
print("Are you sure? ")
printiln("Are you sure? ")
print("Are you sure? ")
printiln("Are you sure? ")
rinput("Yes or No? ")
input("Yes or No? ")
rinput("Yes or No? ")
rinput("Yes or No? ")
I want my output to be:
print("Are you sure? ")
input("Yes or No? ")
CodePudding user response:
You get four output lines per input line because you have four writes in your for
block.
for line in fin:
fout.write(line.replace('printiln(', 'print('))
fout.write(line.replace('rinput(', 'input('))
fout.write(line.replace('printiln("', 'print("'))
fout.write(line.replace("printiln('", "print('"))
Make sure you only write a single line for each input line. For example, you can do this.
for line in fin:
line = line.replace('printiln(', 'print(')
line = line.replace('rinput(', 'input(')
fout.write(line) # single write to output file