Reputation: 365
I'm trying to format my text line by line read from a .txt file. Firstly I'm just trying to figure out how to print just one line, then attempt multiple lines after. I've managed to print the text of one line, but when I try to format it they way I want it to look, a new line is created after I attempt to print the last word of the line (using index of -1). The last word is creating a new line, so I think I need to find a way to read the lines as seperate strings but I'm not sure.
This is the code for my program:
def makeTuple (employee):
myTuple = employee.split(" ")
payroll, salary, job_title, *othernames, surname = myTuple
myTuple = tuple(myTuple)
return(myTuple)
def printTuple (data):
employee_str = "{}, {} {:>8} {} {:>5}"
print(employee_str.format(data[-1], " ".join(data[3:-1], data[0], data[2], data[1]))
get_file = input(str("Please enter a filename: "))
path = get_file + ".txt"
try:
text_file = open(path, "r")
except IOError:
print('The file could not be opened.')
exit()
record = text_file.readline()
myTuple = makeTuple(record)
printTuple(myTuple)
This is the text file I'm reading from:
12345 55000 Consultant Bart Simpson
12346 25000 Teacher Ned Flanders
12347 20000 Secretary Lisa Simpson
12348 20000 Wizard Hermione Grainger
The output I get at the moment is:
Simpson
, Bart 12345 Consultant 55000
Whereas I want it to look like:
Simpson, Bart 12345 Consultant 55000
Upvotes: 0
Views: 343
Reputation: 43544
You are getting a newline after "Simpson"
because that's what's in the text file.
Use the function strip()
(Documentation) to remove the newlines when you read the line.
Change the following one line of code and your program should work.
record = text_file.readline().strip()
Upvotes: 2
Reputation: 5088
You can do it with split and join:
s = '''Simpson
, Bart 12345 Consultant 55000'''
print(''.join(s.split('\n')))
Upvotes: 1