Izzino Izzino - 6 months ago 22
Python Question

How do I concatenate lines from a file onto a single line of code?

I'm new to programming and currently working on problem #269 from r/dailyprogrammer. I want to add the ability to read files and format them based on the indention format given. My current code:

import sys

filename=input("What file would you like to reformat?")
f=open(filename,"r")
n_lines= int(f.readline())
indents=(f.readline())

block=0
for line in f:
line=line.lstrip('·» \t')
if line.startswith('ENDIF') or line.startswith('NEXT'):
block-=1
print(indents*block+line)
if line.startswith('FOR') or line.startswith('IF'):
block+=1


gives me this

VAR I

FOR I=1 TO 31

····
IF !(I MOD 3) THEN

····
····
PRINT "FIZZ"

····
ENDIF

····
IF !(I MOD 5) THEN

····
····
PRINT "BUZZ"

····
ENDIF

····
IF (I MOD 3) && (I MOD 5) THEN

····
····
PRINT "FIZZBUZZ"

····
ENDIF

NEXT


,but I want it to print the pseudo indentions+line on the same line.

Answer

Your indents string ends with a newline, like this: " \n". You want to get rid of that.

indents=f.readline().strip('\n')

When reading from a text file, there will always be a newline character at the end of each line until you've reached the end of the file.

print() will also add a single newline to its output by default. If you don't want that, you can pass an end argument.

print('this line doesn't need another newline.\n', end='')