在Python中,可以使用内置的sorted函数对文件中的内容按字母顺序进行排序。下面是一个示例代码:
file_path = "input.txt"
output_file_path = "output.txt"
# 读取文件内容
with open(file_path, 'r') as file:
lines = file.readlines()
# 对内容进行排序
sorted_lines = sorted(lines)
# 将排序后的内容写入新文件
with open(output_file_path, 'w') as file:
file.writelines(sorted_lines)
在示例代码中,首先使用open
函数打开输入文件,并使用readlines
方法读取文件内容,将每一行作为一个字符串存储在lines
列表中。
然后,使用sorted
函数对lines
列表进行排序,生成一个新的排序后的列表sorted_lines
。
最后,使用open
函数以写入模式打开输出文件,并使用writelines
方法将排序后的内容写入新文件。
注意:示例代码中的file_path
和output_file_path
需要根据实际情况修改为相应的文件路径。
下一篇:按字母顺序对数据类型进行排序