我以前用python编写过一个文件,在第二次尝试运行脚本时,我编写了两次相同的内容。你知道吗
以下是我的文件内容:
Story1: A short story is a piece of prose fiction that typically can be read in one sitting and focuses on a self-contained incident or series of linked incidents, with the intent of evoking a "single effect" or mood, however there are many exceptions to this. A dictionary definition is "an invented prose narrative shorter than a novel usually dealing with a few characters and aiming at unity of effect and often concentrating on the creation of mood rather than plot. Story1: A short story is a piece of prose fiction that typically can be read in one sitting and focuses on a self-contained incident or series of linked incidents, with the intent of evoking a "single effect" or mood, however there are many exceptions to this. A dictionary definition is "an invented prose narrative shorter than a novel usually dealing with a few characters and aiming at unity of effect and often concentrating on the creation of mood rather than plot.
我使用的python Set操作符是这样的,但这不适用于我的情况:
uniqlines = set(open('file.txt').readlines())
bar = open('file', 'w').writelines(set(uniqlines))
在我的例子中,现在有了换行符,所以所有的内容都被读取一次。我想能够删除的内容后,故事1:是遇到第二次。 我该怎么做?你知道吗
你可以使用find方法。你知道吗
更新:由于您不需要换行来拆分文件,因此您最好只对文件进行slurp操作,适当地拆分,然后编写一个新文件。简单的解决方案是:
从技术上讲,这对于实际的电源丢失不是完全安全的,因为在元数据更新发生之前数据可能不会写入磁盘。如果您是偏执狂,请调整它以显式阻止,直到数据同步为止,方法是在从
with
块(在write
块中删除之前)添加以下两行:副本从单独行开始的情况的旧答案:
查找第二个副本的开始位置,并截断文件:
由于您所做的只是从文件末尾删除重复信息,因此这是安全有效的;
truncate
在大多数操作系统上应该是原子的,因此可以一次释放尾部数据,而不存在部分写入损坏等风险。你知道吗相关问题 更多 >
编程相关推荐