【问题标题】:Python: Merging a string with a filePython:将字符串与文件合并
【发布时间】:2015-01-22 20:48:52
【问题描述】:

我有一个这样的文本文件:

2014-12-22 10:55:19 1 https://stackoverflow.com/ 你好,这是另一篇文章...这一篇可能包含\n换行符或两个

2014-12-07 12:02:49 https://stackoverflow.com/ 嗨,这是我的第二篇文章

2014-12-02 12:18:02 https://stackoverflow.com/ 你好这是我的第一篇文章

我想将它与可能不包含所有先前信息的字符串合并
字符串:

2015-01-22 17:05:52 https://stackoverflow.com/ 这将是我的最后一篇文章!再见

2014-12-22 10:55:19 https://stackoverflow.com/ 你好,这是另一篇文章...这一篇可能包含\n换行符或两个

2014-12-07 12:02:49 https://stackoverflow.com/ 嗨,这是我的第二篇文章

我需要我的文本文件包含 4 个唯一条目。我最初的直觉是用空格分割文件,然后用空格分割字符串,然后执行以下操作:

if stringEntry not in fileEntry:
    prepend stringEntry to myFile

我相信一定有更好的方法可以做到这一点,如果您有任何想法,请给我留言。

【问题讨论】:

    标签: python string file merge


    【解决方案1】:

    如果是我,我会将所有字符串放入一个列表中,检查以确保字符串不存在,然后再写入最终输出文件。

        #! /usr/bin/python
    
        f = open('files.txt')
        o = open('output.txt', 'w')
        strings = []
    
        for line in f:
            if line not in strings: strings.append(line)
    
        #I am splitting by newline, you may also be able to split by space, but depends on the string stucture.
        some_string = """line1\nline2\nline3\n"""
    
        elements = some_string.split('\n')
        for each in elements:
            if each not in strings:
                strings.append(each + '\n')
    
        for each in strings:
            o.write(each)
    

    【讨论】:

    • 这完全符合我的预期,非常感谢!记住 f.close() 和 o.close()
    猜你喜欢
    • 2019-04-01
    • 2015-03-20
    • 1970-01-01
    • 2019-03-02
    • 2010-12-13
    • 2023-02-24
    • 1970-01-01
    • 2019-07-21
    • 1970-01-01
    相关资源
    最近更新 更多