【问题标题】:Multiple lists saved in a single text file多个列表保存在单个文本文件中
【发布时间】:2016-04-19 14:03:24
【问题描述】:

我有一个包含以下信息的文本文件(每个条件单独一行):

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 up
20363.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 argv
from itertools import tee, islice, chain, izip
script, from_file, to_file = argv 
print "Here's your file %r:" %from_file

fhand=open(from_file)
total = 0
for 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 words

with open(to_file, 'w') as output:          
      output.write(str(words)+'\n')

fhand.close()
output.close() 

那么,如何将每个条件的数据再次保存在单独的行中(尖括号、逗号等都不是问题)?

['UP_aic', 'up', '920.5', 'down', '17764.5', 'up', '28249.1']  
['DOWN_aic', 'down', '941.0', 'up', '8894.3', 'down', '11691.0', 'up', '20363.1', 'down', '26901.8'] 
['UP_adc', 'down', '1477.1']  
['DOWN_adc', 'up', '1752.8'] 

【问题讨论】:

  • 你的意思是str.join()
  • 您确定要print words,而不是将每个words 附加到list,然后您可以循环并写入文件吗?
  • TigerhawkT3 - 可以删除打印语句,我只是看看我的代码是否符合我的要求。凯文,str.join() 不适用于列表...
  • 我是说“所有前面的行都被下一行删除了,所以只有最后一个保留”的原因可能是因为你只是打印它们而不是实际将它们保存在任何地方,除了words 之外,它会被反复覆盖,因此最终会引用最后一个。
  • TigerhawkT3,我按照你的建议做了一个额外的循环,但是它将所有数据保存到一行中......然后我必须另外操作输出。我的想法是按照问题中的顺序保存这些行。

标签: python list file


【解决方案1】:

write() 的调用在for 循环之外,因此words 仅在循环结束后写入文件。到那时,它包含了最后一行读取的内容。

将您的代码更改为类似

def previous_and_next(some_iterable):
    items, nexts = tee(some_iterable, 2)
    nexts = chain(islice(nexts, 1, None), [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 块的用途。

【讨论】:

    猜你喜欢
    • 2021-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多