Python: 将字符串与文件合并
Python: Merging a string with a file
我有一个这样的文本文件:
2014-12-22 10:55:19 1
https://whosebug.com/
Howdy, this is yet another post... this one might contain a\nline break or two
2014-12-07 12:02:49
https://whosebug.com/
Hi this is my 2nd post
2014-12-02 12:18:02
https://whosebug.com/
Hello this is my first post
我想将它与一个可能不包含所有先前信息的字符串合并
字符串:
2015-01-22 17:05:52
https://whosebug.com/
This is going to be my final post! Bye
2014-12-22 10:55:19
https://whosebug.com/
Howdy, this is yet another post... this one might contain a\nline break or two
2014-12-07 12:02:49
https://whosebug.com/
Hi this is my 2nd post
我需要我的文本文件包含 4 个 unique 条目。我最初的直觉是用白色 space 拆分文件,然后用白色 space 拆分字符串,然后执行以下操作:
if stringEntry not in fileEntry:
prepend stringEntry to myFile
我相信一定有更好的方法来做到这一点,如果您有任何想法请告诉我。
如果是我,我会将所有字符串放入一个列表中,检查以确保字符串不存在,然后再写入最终输出文件。
#! /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)
我有一个这样的文本文件:
2014-12-22 10:55:19 1 https://whosebug.com/ Howdy, this is yet another post... this one might contain a\nline break or two
2014-12-07 12:02:49 https://whosebug.com/ Hi this is my 2nd post
2014-12-02 12:18:02 https://whosebug.com/ Hello this is my first post
我想将它与一个可能不包含所有先前信息的字符串合并
字符串:
2015-01-22 17:05:52 https://whosebug.com/ This is going to be my final post! Bye
2014-12-22 10:55:19 https://whosebug.com/ Howdy, this is yet another post... this one might contain a\nline break or two
2014-12-07 12:02:49 https://whosebug.com/ Hi this is my 2nd post
我需要我的文本文件包含 4 个 unique 条目。我最初的直觉是用白色 space 拆分文件,然后用白色 space 拆分字符串,然后执行以下操作:
if stringEntry not in fileEntry:
prepend stringEntry to myFile
我相信一定有更好的方法来做到这一点,如果您有任何想法请告诉我。
如果是我,我会将所有字符串放入一个列表中,检查以确保字符串不存在,然后再写入最终输出文件。
#! /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)