Home > front end >  Reversing names in file input and output
Reversing names in file input and output

Time:05-03

I am working on a problem in an online MOOC on intro to python programming. I am stuck on how to complete the below problem. Could you please offer some guidance?

The problem is below: You've been sent a list of names. Unfortunately, the names come in two different formats:

First Middle Last Last, First Middle

You want the entire list to be the same. For this problem, we'll say you want the entire list to be First Middle Last.

Write a function called name_fixer. name_fixer should have two parameters: an output filename (the first parameter) and the input filename (the second parameter). You may assume that every line will match one of the two formats above: either First Middle Last or Last, First Middle.

name_fixer should write to the output file the names all structured as First Middle Last. If the name was already structured as First Middle Last, it should remain unchanged. If it was structured as Last, First Middle, then Last should be moved to the end after a space and the comma removed.

The names should appear in the same order as the original file.

For example, if the input file contained the following lines: David Andrew Joyner Hart, Melissa Joan Cyrus, Billy Ray

...then the output file should contain these lines: David Andrew Joyner Melissa Joan Hart Billy Ray Cyrus

Add your code here! My code:

def name_fixer(output_filename, input_filename):
file = open(filename, 'r')
for char in string:
if char == ',':
string.remove(',')
value = string.reverse()
file.close()

CodePudding user response:

input_file.txt

David Andrew Joyner 
Hart, Melissa Joan
Cyrus, Billy Ray
Kevin Pietersen
Rowling, Johanne Kimberley

CODE

def name_fixer(input_file, output_file):
    with open(input_file, "r") as f, open(output_file, "w ") as g:
        for line in f:
            line = line.strip()
            if ',' in line:
                line = ' '.join(line.split(',')[::-1]).strip()
            g.write(f"{line}\n")

myinputfile = "input_file.txt"
myoutputfile = "output_file.txt"
name_fixer(myinputfile, myoutputfile)

output_file.txt

David Andrew Joyner
Melissa Joan Hart
Billy Ray Cyrus
Kevin Pietersen
Johanne Kimberley Rowling
  • Related