阅读python后从文件中删除一行

时间:2015-11-27 14:11:08

标签: python line

如何在阅读或打印后从.txt文件中删除/删除一行

Caused by: org.hibernate.AnnotationException: Unknown mappedBy in: com.xxx.Wrapper.base, referenced property unknown: com.xxx.Base.wrapper
    at org.hibernate.cfg.OneToOneSecondPass.doSecondPass(OneToOneSecondPass.java:153)
    at org.hibernate.cfg.Configuration.originalSecondPassCompile(Configuration.java:1697)
    at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1426)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1846)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1930)
    at org.springframework.orm.hibernate4.LocalSessionFactoryBuilder.buildSessionFactory(LocalSessionFactoryBuilder.java:372)
    at org.springframework.orm.hibernate4.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:453)
    at org.springframework.orm.hibernate4.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:438)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1627)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1564)
    ... 50 more

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

事实上,最好的解决方案是在你不确定之前不要写。如果数据量不是很大,那么最简单的方法就是将它加载到内存中,而不是保存,而不是保存。

lines = []
for x in open("words.txt"):
    lines.append(x)

#do something
#del lines[i] if you don't need them

for x in lines:
    print(x)

如果输入文件很大并且您只需要最后一个值可以擦除,则只能存储最后的值并在不需要时删除它们。保存最后一个值collections.deque非常有用。确切的代码取决于特定的逻辑。

要撤消的唯一一个值,您可以使用此代码

last_line = None
for x in open("words.txt"):
    if last_line is not None:
        print(last_line)
    last_line = x

    #do something
    #you may use continue or break

    #if you need undo "printing":
    #last_line = None
if last_line is not None:
    print(last_line)

答案 1 :(得分:0)

''.join([ x for x in open('file.txt').readlines() if x.strip() ])