繁体   English   中英

如何在排序文件中插入一行?

[英]How insert a line in a sorted file?

我用循环生成了很多字符串,我需要在文件中写这些字符串。 我希望我的文件排序。 以下代码说明了我想要做的事情:

#! /usr/bin/python2.7
# -*- coding: utf-8 -*-
my_file = open('my_file.txt', 'w')

#randon_string and insert_in_order_alphabetically are just for the example
for x in range(1,100000000):
    my_string = random_string()
    my_file.insert_in_alphabetical_order(my_string)

my_file.close()

Python是否具有执行此操作的功能或我是否需要编写自己的算法代码?

最聪明的做法是将文件作为list读取,添加所有额外的字符串,然后在重写文件之前在列表上使用sort

例如给出文件:

c
c
c
a
a
b
a
a

和代码:

lines = []

with open('file.txt','r') as f:
    for line in f:
        lines.append(line.rstrip())

lines.append('z')
lines.append('e')
lines.append('e')

lines.sort()

with open('file.txt', 'w') as f:
    for line in lines:
        f.write(line + "\n")

这会创建文件:

a
a
a
a
b
c
c
c
e
e
z

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM