python – 保存在单个文本文件中的多个列表

python – 保存在单个文本文件中的多个列表,第1张

概述我有一个带有以下信息的文本文件(每个条件在一个单独的行中): UP_aic up 920.5 4 17280.0 down 17764.5 2 28186.5 up 28249.1 DOWN_aic down 941.0 2 8800.5 up 8894.3 down 11691.0 2 20316.2 up20363.1 4 26901.8 down 26901.8 UP_adc do 我有一个带有以下信息的文本文件(每个条件在一个单独的行中):

UP_aic up 920.5 4 17280.0 down 17764.5 2 28186.5 up 28249.1  DOWN_aic down 941.0 2 8800.5 up 8894.3 down 11691.0 2 20316.2 up20363.1 4 26901.8 down 26901.8  UP_adc down 1477.1   DOWN_adc up 1752.8

我已经实现了删除2s和4s的代码以及它们各自的时间(见下文),我想要的是在另一个文本文件中重新保存这些信息!

然而,在今天早上的所有15次(或左右)尝试中,我只设法以各种方式保存最后一行(DOWN_adc up 1752.8):正常,垂直而不是水平,所有字符“粘合”在一起等.等等.

所以我现在保留了最基本的写法.我知道所有以前的行都被下一行删除,所以只留下最后一行,但我无法弄清楚如何防止这种情况.

这是代码:

from sys import argvfrom itertools import tee,islice,chain,izipscript,from_file,to_file = argv print "Here's your file %r:" %from_filefhand=open(from_file)total = 0for line in fhand:      words=line.split()    def prevIoUs_and_next(some_iterable):        items,nexts = tee(some_iterable,2)        nexts = chain(islice(nexts,1,None),[None])        return izip(items,nexts)    for item,nxt in prevIoUs_and_next(words):        if item=='2':            words.remove(item)           words.remove(nxt)        elif item=='4':            words.remove(item)            words.remove(nxt)    print wordswith open(to_file,'w') as output:                output.write(str(words)+'\n')fhand.close()output.close()

那么,如何将这样的数据再次保存在一个单独的行中(尖括号,逗号等不是问题)?

['UP_aic','up','920.5','down','17764.5','28249.1']  ['DOWN_aic','941.0','8894.3','11691.0','20363.1','26901.8'] ['UP_adc','1477.1']  ['DOWN_adc','1752.8']
解决方法 对write()的调用在for循环之外,因此在循环结束后只将字写入文件.到那时,它包含最后一行读取的内容.

将您的代码更改为类似的内容

def prevIoUs_and_next(some_iterable):    items,2)    nexts = chain(islice(nexts,[None])    return izip(items,nexts)with open(to_file,'w') as output:          for line in fhand:          words = line.split()        for item,nxt in prevIoUs_and_next(words):            if item == '2':                 words.remove(item)                words.remove(nxt)            elif item == '4':                words.remove(item)                words.remove(nxt)        print words        output.write(str(words)+'\n')

无需调用output.close(),这就是with block的用途.

总结

以上是内存溢出为你收集整理的python – 保存在单个文本文件中的多个列表全部内容,希望文章能够帮你解决python – 保存在单个文本文件中的多个列表所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/langs/1197507.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存