defsort(): name = input("Please enter the name of the file: ") file_encoding = "utf-8" try: withopen(os.path.join(sys.path[0], name + ".txt"), "r", encoding=file_encoding) as f: data = f.readlines() except FileNotFoundError: print("The file does not exist.") return except UnicodeDecodeError: file_encoding="gbk" withopen(os.path.join(sys.path[0], name + ".txt"), "r", encoding="gbk") as f: data = f.readlines() except: print("The file cannot be read.") return # 对数据进行排序 data.sort() withopen(os.path.join(sys.path[0], name + "_sorted.txt"), "w", encoding=file_encoding) as f: f.writelines(data) print("The data has been sorted successfully.")