I'm a beginner in Python programming. Currently, I learn how to work on the files... I've created a program, which excludes the names (first & last) from each row, that contains both of them. When the pair of names does not include for example the Last Name part, it places n/a in the last_names.txt file.
Like from the file names.txt:
Paul Morgan James Kowalski Thomas
sort to two files
Paul James Thomas
Morgan Kowalski n/a
""" Program separating first names and last names gathered in pairs from one file and saving them into two files. """ "Global Variables:" allNamesFromFile =  def names_separator(fileName): with open(fileName, "r+", encoding="utf-8-sig") as namesFromFile: for names in namesFromFile: allNamesFromFile.append(tuple(names.replace("\n", "").split(" "))) open("last_names.txt", "w").close() #cleaning the last_names.txt file open("first_names.txt", "w").close() #cleaning the first_names.txt file lastNamesFile = open("last_names.txt", "a+", encoding="utf-8-sig") firstNamesFile = open("first_names.txt", "a+", encoding="utf-8-sig") for namesTuples in allNamesFromFile: try: lastNamesFile.write(namesTuples + "\n") except: lastNamesFile.write("n/a\n") try: firstNamesFile.write(namesTuples + "\n") except: firstNamesFile.write("n/a\n") lastNamesFile.close() firstNamesFile.close() print("welcome in the names separator program...") while True: fileName = str(input("Please provide the file name with its extension: ")) try: names_separator(fileName) print("operation completed") break except: print("You have provided an incorrect file name...") continue
I wonder if there is anything I could improve in this code... I wanted to use list + tuples. The program works correctly, but I want to review it and maybe improve if it's possible. Maybe I could write it shorter/better, or just its functionality can be optimized?
Thanks in advance.