<Python>将一个有序排列的txt文件,打乱成无序排列,再输出到指定文件中

功能:

现有一个文件“1.txt”,里面的内容是:

00176480_nohash_0_bed
00176480_nohash_0_down
00176480_nohash_0_left
00176480_nohash_0_marvin
00176480_nohash_0_off
00176480_nohash_0_one
00176480_nohash_1_marvin
004ae714_nohash_0_bed
004ae714_nohash_0_cat
004ae714_nohash_0_down
004ae714_nohash_0_eight
004ae714_nohash_0_five
004ae714_nohash_0_four
004ae714_nohash_0_go
004ae714_nohash_0_left
004ae714_nohash_0_off

需要将里面的排序进行打乱,再存储到“2.txt”文件中

代码写的简单,作为一个C++程序员,正在努力学习python

代码:

import random

def ReadFileDatas():
    FileNamelist = []
    file = open('1.txt','r+')
    for line in file:
        line=line.strip('\n') #删除每一行的\n
        FileNamelist.append(line)
    print('len ( FileNamelist ) = ' ,len(FileNamelist))
    file.close()
    return FileNamelist

def WriteDatasToFile(listInfo):
    file_handle=open('2.txt',mode='a')
    for idx in range(len(listInfo)):
        str = listInfo[idx]
        #查找最后一个 “_”的位置
        ndex = str.rfind('_')
        #print('ndex = ',ndex)
        #截取字符串
        str_houZhui = str[(ndex+1):]
        #print('str_houZhui = ',str_houZhui)
        str_Result = str + ' ' + str_houZhui+'\n'
        print(str_Result)
        file_handle.write(str_Result)
    file_handle.close()

if __name__ == "__main__":
    listFileInfo = ReadFileDatas()
    #打乱列表中的顺序
    random.shuffle(listFileInfo)
    WriteDatasToFile(listFileInfo)

“2.txt”文件的最后结果

102192fd_nohash_0_bed bed
c93d5e22_nohash_2_left left
72aa7259_nohash_0_right right
80c17118_nohash_0_seven seven
15c563d7_nohash_0_dog dog
611d2b50_nohash_3_no no
eb67fcbc_nohash_0_seven seven
b5935410_nohash_0_off off
6846af18_nohash_1_left left
01648c51_nohash_0_nine nine
ceaadb24_nohash_1_bird bird
6ceeb9aa_nohash_0_five five

9e42ae25_nohash_0_marvin marvin


在此,我要特意说明的函数:

random.shuffle(列表)

python很强大,一个函数就可以搞定这个功能。

猜你喜欢

转载自blog.csdn.net/qq_32716885/article/details/80598234